【问题标题】:Float representation of binary in Python (bits not hex)Python中二进制的浮点表示(位不是十六进制)
【发布时间】:2017-03-22 15:41:13
【问题描述】:

如何将字符串的 32 位浮点数表示为二进制 IEEE 754?

例子

'00111111100000000000000000000000' -> 1.00

这个问题与以下问题相反: Binary representation of float in Python (bits not hex) 我在别处找不到答案。请注意,我对编码很陌生,所以请保持温和。

【问题讨论】:

    标签: python binary floating-point


    【解决方案1】:

    使用struct.packstruct.unpack

    >>> import struct
    >>> n = '00111111100000000000000000000000'
    >>> struct.unpack('f', struct.pack('i', int(n, 2)))[0]
    1.0
    
    • int(.., 2) 将二进制表示转换为 int(基数 2)
    • struct.pack('i', ..) 转换字节(i: 32bit int)
    • struct.unpack('f', ...)[0] 将字节转换回浮点数。

    对于其他struct 格式字符,请参见Format charactes - struct module documentation

    【讨论】:

      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      相关资源
      最近更新 更多