c# BitConverter.Python中的ToSingle等价
本文关键字:ToSingle 等价 中的 Python BitConverter | 更新日期: 2023-09-27 18:06:57
我在c#中有一些代码使用BitConverter将字节转换为浮点数。单个函数,如下所示:
float tmp_float = BitConverter.ToSingle(jobBff, cnt);
我从这个链接中发现:
http://en.wikipedia.org/wiki/Single-precision_floating-point_format四个字节(只是不确定顺序),使用1位作为符号,8位作为指数,其余的位作为分数。
在c#中,我只是通知一个缓冲区,起始位置,c#完成剩下的工作。在Python上有等价的函数吗?或者如何将这4个字节转换为浮点数?
谢谢!
解决方案:正如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模块。您可能需要struct.unpack( 'f', buffer )
方法(可能需要一些尾序调整,请参阅文档)。