vlang-转换int,u32,u64,f32,f64等
我有不同数字数据类型的各种变量(int
、u32
、u64
、f32
、f64< /code> 等)并希望将它们转换为字节数组。
例如:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可以使用 encoding.binary.binary 如@adam oates 在评论中。
以下示例是64位数据。 32位和大型的功能也可以使用。
要将
f64
转换为/从字节(u8
)转换,我们可以使用math.f64_bits
和 Math.f64_from_bits 将浮点转换为IEEE 754二进制表示(u64
),后来将其转换为字节。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.