Extracting 3-byte integers

John Machin sjmachin at lexicon.net
Tue Jun 27 03:32:02 CEST 2006


On 27/06/2006 9:59 AM, John Machin wrote:
> On 27/06/2006 9:36 AM, Bob Greschke wrote:
>> I have some binary data read from a file that is arranged like
>>
>>    <3-byte int> <3-byte int> <3-byte int> etc.
>>
>> The "ints" are big-endian and there are 169 of them.  Is there any 
>> clever way to convert these to regular Python ints other than (struct) 
>> unpack'ing them one at a time and doing the math?
>>
> 
> I'd call that "arithmetic", not "math" :-)
> 
> Here's another way, not touted as "clever":
> 
> |>> guff = "\x00\x00\x01\x00\x02\x01\x03\x00\x00\x00\x00\xFF"
> |>> import array
> |>> b = array.array('B', guff)
> |>> actual = [b[x]*65536 + b[x+1]*256 + b[x+2] for x in range(0, len(b), 
> 3)]

Two further points:

(1) If using struct.unpack, it's not necessary to unpack 3 bytes at a 
time; one could substitute b = struct.unpack('507B', guff) in the above.

(2) The OP didn't specify whether the ints were signed or unsigned. The 
above is for unsigned. To convert an unsigned X to signed, here's the 
"math":

if X >= 0x800000: X -= 0x1000000

Cheers,
John



More information about the Python-list mailing list