Parsing a char to u32

As the questions states, how do I achieve this?

If I have a code like this:

let a = "29"; for c in a.chars() { println!("{}", c as u32); } 

What I obtain is the unicode codepoints for 2 and 9:

  • 50
  • 57

What I want is to parse those characters into the actual numbers.

0

2 Answers

char::to_digit(radix) does that. radix denotes the "base", i.e. 10 for the decimal system, 16 for hex, etc.:

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

It returns an Option, so you need to unwrap() it, or better: expect("that's no number!"). You can read more about proper error handling in the appropriate chapter of the Rust book.

7

Well, you can always use the following hacky solution:

fn main() { let a = "29"; for c in a.chars() { println!("{}", c as u32 - 48); } } 

ASCII digits are encoded with values from 48 to 57, so when you have a string containing characters 2 and 9 and attempt to interpret them as integers, you get 50 and 57. To get their expected values you just need to subtract 48 from them.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like