0

I'm trying to use struct.pack to get an integer into a network-order 2 byte string.

struct.pack("!H", -9890)

causes:

error: integer out of range for 'H' format code

What I really mean is struct.pack("!H", -9890 & 0xff), that is, to take the last two bytes of this number. Is there a way to make struct behave in this way without me having to mask the input everytime?

jaynp
  • 3,275
  • 4
  • 30
  • 43

1 Answers1

2

You cannot make struct do the masking for you; you'll need to manually provide integers that fit. If masking numbers with 0xff works for your application, then that is what you'll have to do.

Python will not guess for you here, Python integers are unbounded and providing integers outside of the range of the struct slots is not a job left to guessing. After all, it could be an application error if values outside the range are produced. And if values outside the range should be made to fit, it is up to you to decide how to do so; masking is one way, limiting the values to the boundaries (0 or 255) is another.

To quote two applicable lines from the Zen of Python:

Explicit is better than implicit.

[...]

In the face of ambiguity, refuse the temptation to guess.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • thanks. Shortly after I posted, I came across that here as well: http://stackoverflow.com/questions/20766813/how-to-convert-signed-to-unsigned-integer-in-python – jaynp Nov 30 '14 at 01:48