[Tutor] Dealing with bitfields in Python

Skipper Seabold jsseabold at gmail.com
Sun Aug 30 17:59:06 CEST 2009


Hello all,

Fair warning, I didn't know what a bitfield was a few hours ago.

I am working with a program via the dbus module and I am wondering if
there is built-in support to deal with bitfields in Python.  I query
my application and it returns a bitfield 119.  The bitfield "key" is

NONE                  = 0,
CAN_GO_NEXT           = 1 << 0,
CAN_GO_PREV           = 1 << 1,
CAN_PAUSE             = 1 << 2,
CAN_PLAY              = 1 << 3,
CAN_SEEK              = 1 << 4,
CAN_PROVIDE_METADATA  = 1 << 5,
CAN_HAS_TRACKLIST     = 1 << 6

And a call to the method returns 119.  I have gotten far enough to
understand that 119 is

>>> (1<<0)+(1<<1)+(1<<2)+(0<<3)+(1<<4)+(1<<5)+(1<<6)
119

119 is 01110111 as a binary byte (I'm reaching back to high school
computer science here...)

So I guess I understand the basics of what it's telling me, but I'd
like to unpack 119 into binary, so I can read it and use the
information in my program.  I've adapted a code snippet that I found
online to do this, but I'm wondering if there is a better way in
python maybe using binascii or struct?

Here is the helper function I've adapated

def int_2_binary(int):
    const = 0x80000000
    output = ""
    ## for each bit
    for i in range(1,33):
        ## if the bit is set, print 1
        if( int & const ):
            output = output + "1"
        else:
            output = output + "0"
        ## shift the constant using right shift
        const = const >> 1
    output = list(output)
    output = "".join(output[-8:])
    return output

As you can see const is the smallest signed 32-bit integer, and it
would return a length 32 string.  But I know that my bitfield will be
8-bit, I just don't know what this is in hexadecimal (?) to define
const.  Any pointers to do this in a better way would be appreciated.

Thanks,

Skipper


More information about the Tutor mailing list