我在 C# 中有一些代码使用 BitConverter.ToSingle 函数将字节转换为 float ,如下所示:
float tmp_float = BitConverter.ToSingle(jobBff, cnt);
正如我从这个链接中发现的那样:
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
四个字节进入(只是不确定顺序是什么),使用 1 位作为符号,8 位作为指数,其余位作为小数。
在 C# 中,我只通知缓冲区、起始位置,其余工作由 C# 完成。在 Python 上是否有等效的函数?或者如何将这 4 个字节转换为 float ?
谢谢!
解决方案:正如 Kyle 在回答中所建议的,我最终使用了下面的代码,它对我有用。
def prepare_bytes_on_string(array):
output = ''
for i in range(0, len(array), 1):
#Just as a reminder:
#hex(x) #value: '0xffffbfde1605'
#hex(x)[2:] #value: 'ffffbfde1605'
#hex(x)[2:].decode('hex') #value: '\xff\xff\xbf\xde\x16\x05'
output += hex(array[i])[2:].decode('hex')
return output
bytes_array = [0x38, 0xcd, 0x87, 0xc0]
val = prepare_bytes_on_string(bytes_array)
output = unpack('f', val)
print output
最佳答案
Python 有 struct module .您可能需要 struct.unpack( 'f', buffer )
方法(可能需要进行一些字节序调整,请参阅相关文档)。
关于Python 中的 C# BitConverter.ToSingle 等价物,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061010/