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 use math.f64_bits
and math.f64_from_bits
which converts the float to IEEE 754 binary representation(u64
) which is later converted into bytes.
import encoding.binary
import math
fn convert_u64_to_bytes(u u64) []u8 {
mut b := []u8{len: 8, init: 0}
binary.little_endian_put_u64(mut b, u)
return b
}
fn convert_f64_to_bytes(val f64) []u8 {
u := math.f64_bits(val) // returns IEEE 754 binary representation of f64
return convert_u64_to_bytes(u)
}
fn convert_bytes_to_u64(b []u8) u64 {
return binary.little_endian_u64(b)
}
fn convert_bytes_to_f64(b []u8) f64 {
u := binary.little_endian_u64(b)
return math.f64_from_bits(u)
}
fn main(){
i := i64(-120)
u := u64(1234)
f := f64(-1235.345)
bi := convert_u64_to_bytes(u64(i))
bu := convert_u64_to_bytes(u)
bf := convert_f64_to_bytes(f)
println('$bi\n$bu\n$bf')
i1 := i64(convert_bytes_to_u64(bi))
u1 := convert_bytes_to_u64(bu)
f1 := convert_bytes_to_f64(bf)
println('$i1\n$u1\n$f1')
}
/* OUTPUT
[0x88, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
[0xd2, 0x04, `\0`, `\0`, `\0`, `\0`, `\0`, `\0`]
[{, 0x14, 0xae, G, a, M, 0x93, 0xc0]
-120
1234
-1235.345
*/
At the time of writing this article, V is yet to get a proper release. So the syntax, functions, etc. are subject to changes.