Python 中的 C# BitConverter.ToSingle 等价物

标签 c# python floating-point floating-point-conversion

我在 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/

相关文章:

c# - 我们可以用 C# 为 Excel 编写宏吗

python - Django 错误地期望 id 列

python - Pandas 数据框索引从日期时间中删除日期

c++ - float 和 double 变量中的数字

c - 如何在 C99 中获取带符号的 float 零?

c# - 是否可以更改原始数据类型的默认值?

c# - 向数组添加字节删除大写字母

c# - Entity Framework 6 生成的极其低效的查询

python - 在 Python 中表示二维网格的最有效方法

Python/Numpy 属性错误 : 'float' object has no attribute 'sin'