-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
List from_be_bytes as Alternative in Transmute Docs #71187
Comments
@domenukk I've used let raw_data = &[0x78, 0x56, 0x34, 0x12];
let num = unsafe {
std::mem::transmute::<[u8; 4], u32>(*raw_data)
};
// This result depends on your machine
assert_eq!(num, 0x12345678);
// use from_be_bytes and from_le_bytes instead to produce predictable result
let num = u32::from_le_bytes(*raw_data);
assert_eq!(num, 0x12345678);
let num = u32::from_be_bytes(*raw_data);
assert_eq!(num, 0x78563412); |
@huangjiahua maybe you can also add |
Error: Parsing assign command in comment failed: ...uangjiahua|error: user should start with @ at >|... Please let |
1 similar comment
Error: Parsing assign command in comment failed: ...uangjiahua|error: user should start with @ at >|... Please let |
…=Dylan-DPC Add example in the alternative in std::mem::transmute docs It is safer to use `from_ne_bytes` to convert raw bytes to type like u32. rust-lang#71187
…=Dylan-DPC Add example in the alternative in std::mem::transmute docs It is safer to use `from_ne_bytes` to convert raw bytes to type like u32. rust-lang#71187
Closed by #71315 |
Many code bases I see use
transmute
to convert raw bytes (&[u8]
) tou32
,f64
, etc. - while they could, and probably should, usefrom_le_bytes
orfrom_be_bytes
.The
transmute
docs include a lengthy section about Alternatives, but this obvious one seems to be missing.The text was updated successfully, but these errors were encountered: