Writing bitfields with varying field lengths

Mike C. Fletcher mcfletch at rogers.com
Tue Aug 19 03:16:02 CEST 2003

Grumfish wrote:

> In order to familiarize my self with Flash files and their bytecode 
> I've started to make an assembler. My first problem is writing the 
> bitfields the format uses often. It is a series of fields, each can be 
> a different number of bits, combined into the least amount of bytes 
> possible. Extra bits in the last byte are padded with zeros. I would 
> like to make a function that takes a size and value for each field 
> needed, calculate the amount of needed bytes, place the values, and 
> the nretun a binary string of the resulting bitfield. I am at a 
> complete loss on how to place the values into the field. I've Googled 
> but have found nothing helpful. Can anybody help?

This should help you get started.  There are more efficient ways to do 
the work, but this is easily followed (hopefully):

def packBitField( * items ):
    """Pack any size set of boolean values into binary string"""
    result = []
    items = list(items)
    while len(items)>=8:
        result.append( pack8( items[:8] ) )
        del items[:8]
    if items:
        result.append( pack8( items+([0]*(8-len(items)) ) ))
    return "".join( result )

def pack8( items ):
    """Pack 8 booleans into a byte"""
    value = 0
    for x in range(len(items)):
        value += (not not items[x])<<x
    return chr(value)

if __name__ == "__main__":
    print repr(packBitField( 0 ))
    print repr(packBitField( 1 ))
    print repr(packBitField( 0,1 ))
    print repr(packBitField( 1,1 ))
    print repr(packBitField( 0,0,1 ))
    print repr(packBitField( 1,0,1 ))
    print repr(packBitField( 0,1,1 ))
    print repr(packBitField( 1,1,1 ))
    print repr(packBitField( 0,0,0,0,0,0,0,0,1 ))


  Mike C. Fletcher
  Designer, VR Plumber, Coder

More information about the Python-list mailing list