struct.unpack less than 1 byte

John Machin sjmachin at lexicon.net
Wed Oct 10 06:42:15 EDT 2007


On Oct 10, 8:15 pm, "Guilherme Polo" <ggp... at gmail.com> wrote:
> 2007/10/10, cprogrammer <cprogram... at gmail.com>:
> > i need to read from a file a struct like this [1byte, 12bits, 12bits]
> > reading 1 byte or more is not a problem ... but the 12 bits values
> > are ...
>
> 12bits, 12bits == 3 byes

and 8 + 12 + 12 = 32 :-)

Assuming little-endianess and that all 3 items are unsigned:

>>> import struct
>>> bytes = "\x21\x43\xba\xdc"
>>> i32 = struct.unpack("<I", bytes)[0]
>>> hex(i32)
'0xdcba4321L'
>>> fields = map(int, (i32 & 0xff, (i32 >> 8) & 0xfff, i32 >> 20))
>>> fields
[33, 2627, 3531]
>>> map(hex, fields)
['0x21', '0xa43', '0xdcb']
>>>




More information about the Python-list mailing list