struct.unpack less than 1 byte

C

cprogrammer

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
 
G

Guilherme Polo

2007/10/10 said:
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

12bits, 12bits == 3 byes
 
M

Michal Bozon

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
 
J

John Machin

2007/10/10 said:
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']
 
S

Stargaming

2007/10/10 said:
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`_::
... Octet("spam"), # synonym for BitField("spam", 8)
... BitField("ham", 12),
... BitField("eggs", 12)
... ) Container(eggs = 4095, ham = 4095, spam = 255)

Cheers,
Stargaming

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top