struct->bit access

M

Mike Spindler

I am passing structs via UDP socket to my Python app from an external
C program. The structure is made up almost entirely of bit fields.

struct example:
unsigned int var1 : 3;
unsigned int var2 : 3;
unsigned int var3 : 1;
unsigned int pad1 : 1;
unsigned int var4 : 8;
unsigned int var5 : 16;

Everything I've read so far says this is too complicated and slow for
Python - write it in C. Can someone point me to a good example of
extracting this and rebuilding using only Python?
Thank you! -Mike
 
G

Grant Edwards

I am passing structs via UDP socket to my Python app from an external
C program. The structure is made up almost entirely of bit fields.

struct example:
unsigned int var1 : 3;
unsigned int var2 : 3;
unsigned int var3 : 1;
unsigned int pad1 : 1;
unsigned int var4 : 8;
unsigned int var5 : 16;

Everything I've read so far says this is too complicated and slow for
Python - write it in C.

That depends on how fast it needs to be. I do all sorts of
bit-field stuff in Python, and it's plenty fast enough for me.
Can someone point me to a good example of extracting this and
rebuilding using only Python?

Use &, |, << and >> operators just like you would in C
 
P

Phil Frost

It's not slow or complicated. Try something like this:


import struct

class Example(object):
def __init__(data):
'''data is a string of 4 bytes read from your input socket.'''
(i,) = struct.unpack('!I', data)
self.var1 = i & 7
self.var2 = (i >> 3) & 7
self.var3 = (i >> 6) & 1
self.var4 = (i >> 8) & 0xf
self.var5 = (i >> 16) & 0xff


You might want to change the format string for unpack() depending on the
byte order of the input.
<http://python.org/doc/2.3.4/lib/module-struct.html> has more
information.
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top