How to serialize a u32 into byte array?

I am trying to serialize a u32 number into byte array, but I was not able until now, can someone help me with that?

Thanks

2 Likes

You probably want byteorder. There are examples in the docs.

5 Likes

If you don't want to depend on external libraries:

use std::mem::transmute;
let bytes: [u8; 4] = unsafe { transmute(123u32.to_be()) }; // or .to_le()

Play

5 Likes

Thank you guys, both solutions worked for me.

If don't mind using operators and prefer not to use unsafe, you can do this

fn transform_u32_to_array_of_u8(x:u32) -> [u8;4] {
    let b1 : u8 = ((x >> 24) & 0xff) as u8;
    let b2 : u8 = ((x >> 16) & 0xff) as u8;
    let b3 : u8 = ((x >> 8) & 0xff) as u8;
    let b4 : u8 = (x & 0xff) as u8;
    return [b1, b2, b3, b4]
}
12 Likes

This thread pops in search engines as one of the first hits, so the following might be useful to someone landing here.

From Rust 1.32.0 onward, the integer primitives have a builtin method for converting to a byte array:

fn main() {
    let value: u32 = 0x1FFFF;
    let bytes = value.to_be_bytes();
    println!("{:?}" , bytes);
}

Use to_le_bytes for Little Endian byte order.

No unsafe code and no external libraries needed.

Play

31 Likes

They also have from_{be,le}_bytes() as well-- nice!

2 Likes