Skip to main content
 首页 » 编程设计

python之双解包号出错

2025年02月15日13傻小

我有一些代码如下:

import struct 
 
def Get_Float(paintwear): 
    buf = struct.pack('i', paintwear) 
    item_float = struct.unpack('f', buf)[0] 
    return item_float 
 
paintwear = 1033975072 
item_float = Get_Float(paintwear) 
print(item_float) 

这有效并给我 item_float 作为 0.07871460914611816。但是,我试图通过像这样双重解包来使该数字更具体:

import struct 
 
def Get_Float(paintwear): 
    buf = struct.pack('i', paintwear) 
    item_float = struct.unpack('d', buf)[0] 
    return item_float 
 
paintwear = 1033975072 
item_float = Get_Float(paintwear) 
print(item_float) 

我将 f 更改为 d,现在出现此错误:struct.error: unpack requires a bytes object of length 8

有什么想法吗?谢谢!

请您参考如下方法:

使用 float 格式:

return "{:.22f}".format(item_float) 

其中 22 是小数点后返回的位数(或要求的位数)。