How to serialize a u32 into byte array?


#1

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

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


#3

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


#4

Thank you guys, both solutions worked for me.


#5

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]
}