Convert Hex to ASCII


#1

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?


#2

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));
    }
}

Playground link


#3

rustc-serialize has a module for this.