Code explanation

#1

I read this code, but did not understand it, can anyone explain it pls:

pub fn u32_bytes (u: &u32) -> [u8; 4] {
    [
        (u >> 8 * 0x0) as u8,
        (u >> 8 * 0x1) as u8,
        (u >> 8 * 0x2) as u8,
        (u >> 8 * 0x3) as u8,
    ]
}
#2

Same as this, which IMO is a bit more clear, without the doubt of operator precedence:


fn main() {
    println!("{:X?}", u32_bytes_le(0xF4F3F2F1));
}

pub fn u32_bytes_le(u: u32) -> [u8; 4] {
    [(u >>  0) as u8,
     (u >>  8) as u8,
     (u >> 16) as u8,
     (u >> 24) as u8]
}

(Playground)

Output:

[F1, F2, F3, F4]

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.51s
     Running `target/debug/playground`

1 Like
#3

It splits a 32-bit integer into four bytes. You didn’t specify what specifically you didn’t understand, so I’ll assume you’re asking about the innermost expression.

Given a 32-bit integer u, it shifts the bits right by 0 bits, then 8 bits, then 16 bits, then 24 bits. It then takes each of those and casts to an 8-bit integer, truncating as needed. Or, in other words:

0xddccbbaa,
0xddccbbaa,
0xddccbbaa,
0xddccbbaa,

Shifts into:

0xddccbbaa,
0x00ddccbb,
0x0000ddcc,
0x000000dd,

Then is truncated:

0xaa,
0xbb,
0xcc,
0xdd,
3 Likes
#4

.

1 Like
#5

FWIW Rust 1.32.0 supports this in the standard library: u32::to_le_bytes.

1 Like