Skip to main content
 首页 » 编程设计

python之弃用警告 : struct integer overflow masking is deprecated

2025年05月04日18落叶

我有以下问题。代码如下:

import  binascii, struct 
def crc32up(data): 
    # little endian!! 
    bin = struct.pack ('<I', binascii.crc32 (data)) 
    return string.upper (binascii.hexlify (bin)) 
 
# Generate crc of time code. 
# 
timecrc_code = crc32up(time_code) 

警告是:

 DeprecationWarning: struct integer overflow masking is deprecated 
 timecrc_code = crc32up(time_code) 

是什么导致了这个错误?

请您参考如下方法:

您试图打包到您为它们分配的 4 个字节中的值太大:

>>> import struct 
>>> n = 2 ** 32 
>>> n 
4294967296L 
>>> struct.pack('<I', n - 1) 
'\xff\xff\xff\xff' 
>>> struct.pack('<I', n) 
__main__:1: DeprecationWarning: struct integer overflow masking is deprecated 
'\x00\x00\x00\x00' 

较新的 python 版本 (>= 2.6) 还会警告您接受的值:

>>> import struct 
>>> struct.pack('<I', -1) 
__main__:1: DeprecationWarning: struct integer overflow masking is deprecated 
__main__:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295 
'\xff\xff\xff\xff' 

python 告诉您的是,它必须屏蔽值以适合 4 个字节;您可以使用 value & 0xFFFFFFFF 自行执行此操作。

警告仅在 python 程序执行期间发出一次。

请注意,从 2.6 开始,binascii.crc32 值始终是一个有符号 4 字节值,您应该始终使用掩码来打包这些值。这在 2.6 之前并不总是一致的,并且取决于平台。参见 the documentation了解详情。