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)
}
>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:
🌸