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

时间:2017-03-24 23:18:13

标签: python-2.7 struct.pack

我正在使用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

1 个答案:

答案 0 :(得分:1)

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

也许你想要无符号短片? H中的struct.packhttps://docs.python.org/2/library/struct.html#format-characters

编辑:即便如此,最大范围内的值(65792)将溢出无符号短 - 你需要一个更大的容器,如int(i)或unsigned int(I)使用这些值