And convert a number to a byte array?
I'd like to avoid using transmute
, but it's most important to reach maximum performance.
There is T::from_str_radix
to convert from a string (you can choose the base and T
can be any integer type).
To convert an integer to a String
you can use format!
:
format!("{:x}", 42) == "2a"
format!("{:X}", 42) == "2A"
To reinterpret an integer as bytes, just use the byte_order
crate.
Old answer, I don't advise this any more:
If you want to convert between u32
and [u8; 4]
(for example) you can use transmute
, it’s what it is for.
Note also that Rust has to_be
and to_le
functions to deal with endianess:
unsafe { std::mem::transmute::<u32, [u8; 4]>(42u32.to_le()) } == [42, 0, 0, 0]
unsafe { std::mem::transmute::<u32, [u8; 4]>(42u32.to_be()) } == [0, 0, 0, 42]
unsafe { std::mem::transmute::<[u8; 4], u32>([0, 0, 0, 42]) }.to_le() == 0x2a000000
unsafe { std::mem::transmute::<[u8; 4], u32>([0, 0, 0, 42]) }.to_be() == 0x0000002a