I’m doing some simple programming puzzles and there’s one part that I’m struggling with – converting hexadecimal values in a Vec
of &str
's to their ASCII char
equivalents. Does there exist an idiomatic method of escaping hexadecimal notations, like d4
, into it’s ASCII equivalent?
You can use u8::from_str_radix
to convert a pair of hex digits to an 8-bit integer, and then you can use as char
to convert that to a char
if you want:
fn hex_to_char(s: &str) -> Result<char, std::num::ParseIntError> {
u8::from_str_radix(s, 16).map(|n| n as char)
}
fn main() {
let v = vec!["4a", "4b", "4c"];
for s in v {
println!("{:?}", hex_to_char(s));
}
}
@mmstick not sure that I understand what you want,
do you need it during compilation or at runtime?
At compilation phase you can use \x
:
fn main() {
let s: &str = "\x43";
println!("s = {}, {:x}", s, s.as_bytes()[0]);
}