I have this code:
let x: [u8; 4] = [0b10111011, 0b00110110, 0b11100010, 0b00010001];
let mut y: [u32; 1] = [0];
unsafe {
std::ptr::copy(x.as_ptr() as *const u32, y.as_mut_ptr(), 1);
}
println!("{:b}", y[0]);
The print statement outputs 10001111000100011011010111011
, which means y[0]
is getting read in the reverse order I need it.
I want y
to basically just be [0b10111011_00110110_11100010_00010001]
.
I know this has to do with endianness, but I don't know how to achieve this. Any help is greatly appreciated.
CodePudding user response:
This is indeed because of your computer storing and reading integers in little endian byteorder, but you specified x
in big endian fashion.
Try using u32::from_be_bytes() which avoids the unsafe
block and always converts x
into the correct u32
representation, whether on a little or big endian machine.
let y = u32::from_be_bytes(x)