【问题标题】:Python binary float to integer conversion using ctypes使用 ctypes 将 Python 二进制浮点数转换为整数
【发布时间】:2020-07-30 10:49:00
【问题描述】:

请帮我理解这段代码sn-p:

def binary_float_to_int(float_number: float) -> int:

    return ctypes.c_uint.from_buffer(ctypes.c_float(float_number)).value

这些输入的结果:

print(binary_float_to_int(7.1746481e-43)) 
print(binary_float_to_int(5.3809861e-43))

是:512 & 384

为什么简单的 Python 转换 int(7.1746481e-43) 不起作用? 还有其他方法可以进行这种类型的转换吗?

【问题讨论】:

  • int(7.1746481e-43) 据我所知工作正常。 int() 向零舍入,7.1746481e-43 小于 1。我不确定 binary_float_to_int() 在做什么,但 7.1746481e-43512 相差甚远。
  • @brunns 转换为表示该浮点数的 32 位 IEEE 754 浮点值的 32 位整数值。

标签: python floating-point type-conversion ctypes


【解决方案1】:

ctypes 代码是:

  1. 将浮点数放入 32 位 C(IEEE 754 格式)ctypes.c_float(float_number)
  2. 将相同的 4 字节值视为 C 无符号整数。 ctypes.c_uint.from_buffer()
  3. 提取无符号整数值.value

如果您希望将这些浮点数的原始 32 位值表示为整数,那么您的数字是正确的。这是另一种方法:

>>> import struct
>>> struct.unpack('i',struct.pack('f',7.1746481e-43))[0]
512
>>> struct.unpack('i',struct.pack('f',5.3809861e-43))[0]
384

这些生成 4 字节的 float32 值,然后将其解压缩为整数。

7.1746481e-43 是一个接近于零的非常小的值。 int() 返回整数部分...在本例中为零,因此也符合预期。

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 2014-11-24
    • 2017-06-24
    • 2013-01-13
    • 1970-01-01
    • 2016-11-02
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多