Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

struct.unpack less than 1 byte

2 views
Skip to first unread message

cprogrammer

unread,
Oct 10, 2007, 5:57:03 AM10/10/07
to
hello all,

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 ...

thanks

Guilherme Polo

unread,
Oct 10, 2007, 6:15:25 AM10/10/07
to cprogrammer, pytho...@python.org
2007/10/10, cprogrammer <cprog...@gmail.com>:
> --
> http://mail.python.org/mailman/listinfo/python-list
>

12bits, 12bits == 3 byes

--
-- Guilherme H. Polo Goncalves

Michal Bozon

unread,
Oct 10, 2007, 6:32:25 AM10/10/07
to
You are able to read single bits from file in C ?

You'll have to read the bytes and than perform some bitwise operations on
them to extract the bits

John Machin

unread,
Oct 10, 2007, 6:42:15 AM10/10/07
to
On Oct 10, 8:15 pm, "Guilherme Polo" <ggp...@gmail.com> wrote:
> 2007/10/10, cprogrammer <cprogram...@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']
>>>

Stargaming

unread,
Oct 10, 2007, 10:00:40 AM10/10/07
to
On Wed, 10 Oct 2007 03:42:15 -0700, John Machin wrote:

> On Oct 10, 8:15 pm, "Guilherme Polo" <ggp...@gmail.com> wrote:
>> 2007/10/10, cprogrammer <cprogram...@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 :-)

[snipped bitfiddling]

Or, if you're doing more of those parsing tasks (or just dislike bit
shifting), you could have a look into `construct`_::

>>> from construct import *
>>> foo = BitStruct("foo",
... Octet("spam"), # synonym for BitField("spam", 8)
... BitField("ham", 12),
... BitField("eggs", 12)
... )
>>> foo
Buffered('foo')
>>> foo.parse("\xff\xff\xff\xff")
Container(eggs = 4095, ham = 4095, spam = 255)

Cheers,
Stargaming

.. _construct: http://construct.wikispaces.com/

0 new messages