Python struct.pack() data range error

Mine picture Mine · Mar 25, 2017 · Viewed 8.3k times · Source

I'm using python2.7 and I have this code. Data values are range from 0 to 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)]):

and gives me this error:

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

Answer

Anthony Sottile picture Anthony Sottile · Mar 25, 2017

SHRT_MAX is defined as 0x7FFF (32767) as shorts are signed: https://en.wikibooks.org/wiki/C_Programming/C_Reference/limits.h

Perhaps you want unsigned short? H in struct.pack: https://docs.python.org/2/library/struct.html#format-characters

EDIT: even then, A value at your maximum range (65792) will overflow unsigned short -- you'll need a larger container such as int (i) or unsigned int (I) to work with those values