Reputation: 795
I need to examine the bytes that make up a character. I know it is possible to do so by going from a char
to a String
to a &[u8]
like so:
let multi_byte_char = 'á';
let little_string = multi_byte_char.to_string();
let byte_slice = little_string.as_bytes();
for byte in byte_slice {
println!("{}", byte); // Prints "195, 161"
}
Is there a way to go straight from a char
to a &[u8]
? I can't find anything in the char documentation. Another option is to mem::transmute
from a char
to a [u8; 4]
, but using unsafe code here seems silly.
EDIT: There is an unstable encode_utf8
method on char
.
Upvotes: 10
Views: 18545
Reputation: 38576
It seems to me like what you want is encode_utf8
, but that is also unstable. You can see its implementation here.
Upvotes: 5