DeprecationWarning:不建议使用struct integer overflow masking

use*_*841 1 python struct

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

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)
Run Code Online (Sandbox Code Playgroud)

并且警告是:

 DeprecationWarning: struct integer overflow masking is deprecated
 timecrc_code = crc32up(time_code)
Run Code Online (Sandbox Code Playgroud)

导致此错误的原因是什么?

Mar*_*ers 6

您尝试打包到为其分配的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'
Run Code Online (Sandbox Code Playgroud)

较新的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'
Run Code Online (Sandbox Code Playgroud)

python告诉你的是它必须屏蔽该值以适应4个字节; 你可以自己做value & 0xFFFFFFFF.

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

请注意,从2.6开始,该binascii.crc32值始终是带符号的 4字节值,您应始终使用掩码来打包这些值.这在2.6之前并不总是一致的,并且取决于平台.有关详细信息,请参阅文档