如何在 Rust 中将 UTF-8 十六进制值转换为 char?

ynn*_*ynn 2 unicode rust

我有一个 Unicode 字符的十六进制值。如何将其转换为charRust 格式?

char::from_u32()不起作用,因为char似乎不包含十六进制值:

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

    let c = '';
    println!("{}", c as u32); //=> 127800 (not 4036988088)
}
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 6

正如其他人指出的那样,该u32值不是代码点,而是当视为大端时的 UTF-8 字节序列。

u32::to_be_bytes()您可以通过结合以下方式将此值转换为字符串std::str::from_utf8()

fn main() {
    let utf8_u32: u32 = 0xf09f8cb8;
    let utf8_bytes = utf8_u32.to_be_bytes();
    let s = std::str::from_utf8(&utf8_bytes);
    
    assert_eq!(s, Ok(""));
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ica 5

您的代码将十六进制值视为 Unicode 代码点,但它们实际上是表情符号的 UTF-8 编码。要对其进行解码,请将字节存储为字节字符串并调用std::str::from_utf8.

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

输出:

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

操场