将浮点(32 位)和双精度(64 位)转换为字节

converting float (32 bit) and double (64 bit) to bytes

提问人:Thomas 提问时间:10/5/2023 最后编辑:mkrieger1Thomas 更新时间:10/5/2023 访问量:42

问:

我正在尝试通过TCP将数据缓冲区从Python发送到C++服务器。

TCP 包顺序定义如下:

  1. bytes[0 till 3] 必须是一个整数(32 位),其值 = 缓冲区的长度
  2. bytes[4 到 7] 必须是浮点数(32 位)
  3. bytes[8 到 15] 必须是双精度(64 位)

我通过以下方式成功实现了第一点(缓冲区的长度)。

buffer = bytearray(bufferLength)  # bufferLength is an integer
buffer[0] = bufferLength.to_bytes(4, 'little')[0]
buffer[1] = bufferLength.to_bytes(4, 'little')[1]
buffer[2] = bufferLength.to_bytes(4, 'little')[2]
buffer[3] = bufferLength.to_bytes(4, 'little')[3]

这很完美。 但是如何转换两个浮点数(32 位和 64 位)呢?

Python 浮点 字节

评论

2赞 Brian61354270 10/5/2023
无需重新发明轮子 - docs.python.org/3/library/struct.html
0赞 Thomas 10/5/2023
多谢!这就是我要找的=)
1赞 mkrieger1 10/5/2023
这回答了你的问题吗?将 python float 转换为字节

答: 暂无答案