bitshit in Python

Gerhard Häring gerhard.nospam at bigfoot.de
Sat May 26 09:43:37 EDT 2001


On Sat, 26 May 2001 15:27:23 +0200, Gorny <gorny at hobbiton.org> wrote:
>Hello,
>
>I've got the following code in C and it works perfect.. :)
>
>----code----
>#include <stdio.h>
>
>struct structje {
>unsigned char eerste:4, tweede:4;
>};
>
>struct structje blaatje;
>
>void blaat(void) {
>blaatje.eerste = 5;
>blaatje.tweede = 4;
>}
>
>int main(void) {
>blaat();
>return 0;
>}
>----end-of-code----
>
>But now I wanted to achieve the same goal in Python. I've search
>through several manuals and the site but couldn't find anything
>useful. Does anybody have an idea about how to put two unsigned
>chars into one byte in Python???

Yes, it seems that it's currently not possible with the struct module. A
quick-and-dirty piece of code that does the same in Python would be:

##################################
class HalfBytes:
    def __init__( self ):
        self.val = 0

    def __setattr__( self, attr, value ):
        if attr == 'first':
            self.val = ( self.val & 0x0F ) | ( value << 4 )
        elif attr == 'second':
            self.val = ( self.val & 0xF0 ) | ( value )
        elif attr == 'val':
            self.__dict__[ 'val' ] = value

x = HalfBytes()
x.first = 0x05
x.second = 0x04
print hex( x.val )
##################################

It could be a start. The proper solution would perhaps be to improve on the
struct module or write a class where the bit offsets and the length of the bit
fields are configurable.

Gerhard
-- 
mail:   gerhard <at> bigfoot <dot> de       registered Linux user #64239
web:    http://highqualdev.com              public key at homepage
public key fingerprint: DEC1 1D02 5743 1159 CD20  A4B6 7B22 6575 86AB 43C0
reduce(lambda x,y:x+y,map(lambda x:chr(ord(x)^42),tuple('zS^BED\nX_FOY\x0b')))



More information about the Python-list mailing list