Need to convert an arbitrary byte-pair to an int.

Alex Martelli aleax at aleax.it
Thu Aug 7 08:30:06 EDT 2003


Graham Nicholls wrote:

> I'm trying to size a jpeg file.  The file size is held in a short (2 byte
> integer) at a certain offset.  Once I've found these two bytes (they're in
> MSB,LSB order), I need to convert them to an integer - now I know that in
> C I'd just cast a pointer to the offset to a short, and that python
> doesn't
> cast, so how can I extract the value from a stream of bytes.  I've looked
> at python.org/Doc/current (I'm using 2.3b1), but can't find anything
> obvious.

I see you've already been pointed to a 3rd party package that's useful for
handling images, but just in case you to need to solve in the future the
actual problem you pose in the subject, one elementary way might be:

thefile = open('whatever', 'rb')
thefile.seek(theoffset)
msb = thefile.read(1)
lsb = thefile.read(1)
theint = ord(lsb) + ord(msb) * 256

The struct module, which I see has also been pointed out to you already,
would let you compact the last three statements into one.  So, in this
specific case, would the array module.  Both struct and array are part
of the standard Python library and often come in handy for occasional
needs of low-level access, such as this.


Alex





More information about the Python-list mailing list