Python: Extracting bits from a byte

Python: Extracting bits from a byte

The classic approach of checking whether a bit is set, is to use binary and operator, i.e.

x = 10 # 1010 in binary
if x & 0b10:  # explicitly: x & 0b0010 != 0
    print(First bit is set)

To check, whether n^th bit is set, use the power of two, or better bit shifting

def is_set(x, n):
    return x & 2 ** n != 0 

    # a more bitwise- and performance-friendly version:
    return x & 1 << n != 0

is_set(10, 1) # 1 i.e. first bit - as the count starts at 0-th bit
>>> True

You can strip off the leading bit using a mask ANDed with a byte from file. That will leave you with the value of the remaining bits:

mask =  0b01111111
byte_from_file = 0b10101010
value = mask & byte_from_file
print bin(value)
>> 0b101010
print value
>> 42

I find the binary numbers easier to understand than hex when doing bit-masking.

EDIT: Slightly more complete example for your use case:

LEADING_BIT_MASK =  0b10000000
VALUE_MASK = 0b01111111

values = [0b10101010, 0b01010101, 0b0000000, 0b10000000]

for v in values:
    value = v & VALUE_MASK
    has_leading_bit = v & LEADING_BIT_MASK
    if value == 0:
        print EOL
    elif has_leading_bit:
        print leading one, value
    elif not has_leading_bit:
        print leading zero, value

Python: Extracting bits from a byte

If I read your description correctly:

if (byte & 0x80) != 0:
    num_bytes = byte & 0x7F

Leave a Reply

Your email address will not be published.