Need to convert an arbitrary byte-pair to an int.
Graham Nicholls
graham at rockcons.co.uk
Thu Aug 7 09:44:16 EDT 2003
<posted & mailed>
Alex Martelli wrote:
> 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
^^^^^^^^^^^^^^^^^
This is what I was trying to do, only getting confused with abs, atoi and
various other invocations which either dont exist or don't do what I wanted
them to.
>
> The struct module, which I see has also been pointed out to you already,
> would let you compact the last three statements into one.
And IMO is rather more elegant.
> 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.
Trouble is, you don't know what you don't know, and my python library
reference is at home, and I'm onsite.
>
>
> Alex
Alex (and Richard),
Thanks for that. The struct module was just what I was after. (I cancelled
my reply which implied that the 3rd party module was the answer, when in
fact, I'd meant to say that using struct is _exactly_ what I want).
Jpeg files have a header, then a series of segments, each of which contains
within it the segment size, so using a struct (just like in c, really) is a
great way to read the segment type and size.
BTW, I posted a month or so back wondering about the merits of Python, which
I already much prefer to perl, but I've sort of simultaneously been
learning Ruby & Python. Not sure which I prefer, yet, but I think that a
reasonable knowledge of both, perhaps with in depth understanding of one of
them, would be useful. Python seems to have more modules, and I do like
lots of things about it, but Ruby _seems_ cleaner, somehow. Its an
interesting exercise, trying to learn both (whilst being quite busy).
Thanks again.
--
Graham Nicholls
Rock Computer Consultancy
More information about the Python-list
mailing list