I have various variables of different numeric datatypes(int
,u32
,u64
,f32
,f64
, etc) and want to convert them to an array of bytes.
For example:
a := 120 // int datatype
a_bytes = some_function(a) // What to do here?
println(a_bytes)
// [ x, `\0`, `\0`, `\0`] should be the output in little endian format
// OR b'x\x00\x00\x00' as a binary string
In python, it can be done as shown in these posts: here and here
This can be done using encoding.binary as mentioned by @Adam Oates in the comments.
The following example is for 64-bit data. Similar functions are available for 32-bit and big-endian also.
To convert
f64
to/from bytes(u8
) we can usemath.f64_bits
andmath.f64_from_bits
which converts the float to IEEE 754 binary representation(u64
) which is later converted into bytes.