Skip to content

String::from_utf16be

String methods · Strings

Level: reference · for working programmers

One line: Decodes big-endian UTF-16 from a &[u8] — the network byte order, and what a BOM-less UTF-16 file is presumed to be by some specifications.

pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>

Stable since 1.98.0.

The mirror of from_utf16le. Same failure modes: an odd byte count, or an unpaired surrogate.

Getting the endianness wrong does not error — it decodes to different characters, usually CJK-range nonsense, because almost any byte pair is a valid code unit in either order. That silence is why the byte order has to come from the format, a BOM, or a specification, and never from a guess.

Stable since Rust 1.98.

Example

string_from_utf16be.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    // "hi" big-endian: 0x00 0x68, 0x00 0x69
    let be = [0x00, 0x68, 0x00, 0x69];
    println!("{:?}", String::from_utf16be(&be));

    // The wrong endianness succeeds, with different characters -- no error.
    println!("{:?}", String::from_utf16le(&be));

    // Which is why the byte order must come from the format, not a guess.
    let text = "hi";
    let le: Vec<u8> = text.encode_utf16().flat_map(u16::to_le_bytes).collect();
    let be2: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
    println!("{le:?} vs {be2:?}");
    println!("{:?} {:?}", String::from_utf16le(&le), String::from_utf16be(&be2));

    // An odd byte count is refused.
    println!("{:?}", String::from_utf16be(&[0x00, 0x68, 0x00]).is_err());
}

Verified output of string_from_utf16be.rs — regenerated by tools/run_examples.py, never hand-typed.

Ok("hi")
Ok("栀椀")
[104, 0, 105, 0] vs [0, 104, 0, 105]
Ok("hi") Ok("hi")
true

See also

String::from_utf16be in the standard library ↗

Po polsku

Najważniejsza rzecz na tej stronie dotyczy nie tyle big-endian, ile ciszy: odczytanie tych samych bajtów w odwrotnej kolejności nie jest błędem. [0x00, 0x68, 0x00, 0x69] to Ok("hi") przez from_utf16be i równie „poprawne” Ok("栀椀") przez from_utf16le — prawie każda para bajtów jest sensowną jednostką kodową w obu kolejnościach, więc zamiast Err dostajesz krzaczki z zakresu CJK. Stąd reguła: kolejność bajtów musi wynikać z formatu, ze znacznika BOM albo ze specyfikacji, nigdy ze zgadywania — a jeśli masz już gotowe u16, ta decyzja zapadła wcześniej i wystarczy from_utf16. Naprawdę wykrywalne zostają tylko dwa błędy: nieparzysta liczba bajtów i niesparowany surogat.

Szukaj po polsku: kolejność bajtów · znacznik BOM · krzaczki zamiast polskich znaków · rust String::from_utf16be · rust utf16 endianness