2

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?

Jimbo
  • 85
  • 7
  • Byte or bit? Your title and first part of the question talks about bits, but the last sentence talks about bytes. – Lev M. Dec 01 '20 at 19:57
  • 1
    Do you know how you can construct the number 0b1111000000000 from i=4 and j=9? – mkrieger1 Dec 01 '20 at 20:03
  • 1
    Does this answer your question? [Algorithm to generate bit mask](https://stackoverflow.com/questions/1392059/algorithm-to-generate-bit-mask) – mkrieger1 Dec 01 '20 at 20:05
  • mkrieger thanks for the helpful question. I think I would take 2 to the power of i, subtract 1, and then left shift it by 9 places. So that should let me create the mask. I'll play with it a bit and also check the link you left. – Jimbo Dec 01 '20 at 20:12

1 Answers1

0

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
Jimbo
  • 85
  • 7