Python struct.pack()数据范围错误

Python struct.pack() data range error

我正在使用 python2.7,我有这段代码。数据值的范围是 0 到 65792。

data_length=30
code=202
data=[51400,31400,100,51400,31400,100,51400,31400,100]
checksum = 0
total_data = ['$', 'M', '<', data_length, code] + data
for i in struct.pack('<2B%dh' % len(data), *total_data[3:len(total_data)]):
    checksum = checksum ^ ord(i)
total_data.append(checksum)
try:
    b = None
    b = self.ser.write(struct.pack('<3c2B%dhB' % len(data), *total_data))
except Exception, error:
    print "\n\nError in sendCMD."
    print "("+str(error)+")\n\n"
    pass

struct.pack('<2B%dh' % len(data), *total_data[3:len(total_data)]):

并给我这个错误:

for i in struct.pack('<2B%dh' % len(data), *total_data[3:len(total_data)]):
struct.error: short format requires SHRT_MIN <= number <= SHRT_MAX

SHRT_MAX 定义为 0x7FFF (32767),因为短裤已签名:https://en.wikibooks.org/wiki/C_Programming/C_Reference/limits.h

也许你想要 unsigned short? Hstruct.pack 中:https://docs.python.org/2/library/struct.html#format-characters

编辑:即便如此,最大范围 (65792) 的值也会溢出 unsigned short——您需要更大的容器,例如 int (i) 或 unsigned int (I) 使用这些值