How do I convert [49]
buffer byte to number 1u32
without using String?
fn main() {
// string "1"
let buf: &[u8] =[49];
// not working, expecting [0,0,0,1] to have good result.
let num = u32::from_ne_bytes(buf.try_into().unwrap());
println!("{}", num);
}
Result:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: TryFromSliceError(())', src/main.rs:7:49
expected result num: u32 = 1u32;
Assuming you only have one byte, you can convert it to char first, then convert it to a digit.
fn main() {
let buf: &[u8] = &[49];
let num = (buf[0] as char).to_digit(10).unwrap();
println!("{}", num);
}
Output:
1