Confuse with the behavior of as between *const u16 and &const u8

fn main() {
    let ptr: *const u16 = Box::leak(Box::new(0b00001001_00000011)) ;
    let u8_ptr = ptr as *const u8;

    unsafe {
        println!("Low byte: {}", *u8_ptr);   
        println!("Howbyte: {}", *u8_ptr.offset(1));
    }
}

(Playground)

and why read low byte first and read hight byte after offset 1?, just opposite with my imagation

Because the code is running on a Little Endian machine, which stores values least-significant byte first. If you ran it on a Big Endian machine, the bytes would be in the opposite order.

It's just how the hardware works.

3 Likes

Most (or essentially all?) modern processors are little-endian architectures meaning that the "lower" bytes of a number come first in memory.

You can also see this reflected in API such as u16::to_ne_bytes which offers a conversion of u16 to [u8; 2] according to the platform's endianness that it's running on, and this method is accompanied by le and be alternatives for when a fully platform independent conversion is needed. As far as I know, e. g. in network protocols, big endian is standard.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.