Why I am getting an error while unwrapping .to_digit option called on char?

Viewed 170

I am trying to parse a single char variable into ASCII value, but all the time I am getting an error.

Basing on answer of hansaplast from this post Parsing a char to u32 I thought this code should work:

let char_variable = 'a';
let shoud_be_u32_varaible = a.to_digit(10).unwrap();

But this code will always throw this error:

thread 'main' panicked at 'called Option::unwrap() on a None value'

For this, code example (example provided in answer of hansaplast):

let a = "29";
for c in a.chars() {
    println!("{:?}", c.to_digit(10));
}

This .to_digit() method will work.

In both cases I am using on .to_digit(10) on variables which are type of char, but for my example this code throws an error and for the code from hansaplast this works. Can someone explain to me what is the difference between those examples and what I am doing wrong because now I am super confused?

Both examples can be found there: Rust playground example


Is using casting in this case will be ok?

let c = 'a';
let u = c as u32 - 48;

If not, can you tell me, what is recommended of doing this?

1 Answers

Okay, I think you are confusing type casting and integer parsing.

to_digit is an integer parsing method. It takes the character and given a radix determines its value in that base. So 5 in base 10 is 5 and is stored as 00000101. 11 in base 15 is stored in memory as 00010000.

Type casting of primitives in rust like 'c' as u32 is probably more what you are after. It's distinct from integer parsing in the sense that you don't care about the "meaning" of the number what you care about is the value of the bits that represent it in memory. This means that the character 'c' is stored as 1100011 (99).

If you only care about ascii characters you should also check char.is_ascii() before doing your conversion. That way you can store your results in a u8 instead of a u32

fn print_ascii_values_of_characters(string: &str) {
  for c in string.chars() {
        if c.is_ascii() {
            println!("{:b}", c as u8) // :b prints the binary representation
        }
    }
}
Related