Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert UTF-8 hex value to char in Rust?

I have a hex value of a Unicode character. How can I convert it to charin Rust?

char::from_u32() didn’t work because char didn’t seem to contain a hex value:

fn main() {
    let code_point: u32 = 0xf09f8cb8; //emoji '🌸'
    println!("{}", code_point); //=> 4036988088

    let c = '🌸';
    println!("{}", c as u32); //=> 127800 (not 4036988088)
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your code treats the hex values as a Unicode code point, but they’re actually the emoji’s UTF-8 encoding. To decode it, store the bytes as a byte string and call std::str::from_utf8.

let bytes: &[u8; 4] = b"\xf0\x9f\x8c\xb8";
let string: &str = std::str::from_utf8(bytes)?;
println!("{}", string);

Output:

🌸

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading