【问题标题】:Convert integer back to 32-bit hex representation then to float?将整数转换回 32 位十六进制表示然后浮点?
【发布时间】:2017-02-21 07:00:10
【问题描述】:

假设我有一些二进制数据被转换为 32 位整数而不是 32 位浮点(小端序),我该如何纠正这个问题?

例如:1155186688 应该是 1750 浮点数(00 C0 DA 44 十六进制)。

【问题讨论】:

    标签: python


    【解决方案1】:

    Struct 用于将类型打包和解包为字节。

    将整数转换回字节,然后转换为浮点数:

    struct.unpack('f', struct.pack('I', 1155186688))[0]
    

    或长格式:

    >>> my_bytes = struct.pack('I', 1155186688) # 'I' = Unsigned Int
    b'\x00\xc0\xdaD'
    >>> my_float = struct.unpack('f', my_bytes)[0] # 'f' = float
    1750 
    

    【讨论】:

    • 仅供参考:这将返回一个元组。您(可能)想在它前面贴上(result,) = 以将其解压缩为合理的值。
    • @Kevin struct.unpack('f', struct.pack('I', 1155186688))[0] 也不会这样做吗?
    • @Aemyl:是的,但我个人认为零在这种情况下是一个丑陋的神奇数字。
    • 而对于 Python 3,(1155186688).to_bytes(8, 'little') 可以替换 struct.pack(),虽然似乎没有对应的 float.from_bytes()...
    猜你喜欢
    • 2011-03-05
    • 2011-04-30
    • 2014-03-01
    • 2020-11-12
    • 1970-01-01
    • 2018-04-20
    • 2010-12-08
    • 1970-01-01
    相关资源
    最近更新 更多