pulling arbitrary bit length integer out of an integer bit field in python

Viewed 100

I have an integer coming out of a hardware device that has several values embedded in it as arbitrary length bit fields.

For example, I have a "status" value that is a 16 bit integer with several values inside of it. One is a 4 bit integer beginning on the third bit.

I'm extracting it using a function I wrote:

def vnGetFieldFromStatus(status):
    return ((status & 0b0001111000000000)>> 9)

This, I believe, is working fine.

Is there a generalized pythonic way to grab an int composed of i bytes starting at byte j?

1 Answers

I worked out a couple of functions to help me:


# pulls an arbitrary number of bits out of a 16 bit field and returns an int with the values
def extractIntFrom16BitField(bitfield, startbit, nbits):
    if startbit<0:
        startbit=15+startbit
    if (startbit+nbits)>16:
        return 0
    rightPad=16-(startbit+nbits)
    if rightPad<0:
        return 0
    mask = ((pow(2,nbits)-1)<<rightPad)
    return((bitfield & mask) >> rightPad)

# Returns a list of ints, each extracted according to the input list of field lengths
# e.g. extractAllFieldsFrom16BitField(0b1010101000001100,[2,1,4,1,8])
#   returns [2,1,5,0,12]
def extractAllFieldsFrom16BitField(bitfield, listOfLengths):
    startpos=0
    returnVal=[]
    for l in listOfLengths:
        returnVal.append(extractIntFrom16BitField(bitfield, startpos, l))
        startpos=startpos+l
    return returnVal
Related