I'm reading a binary file in python and the documentation for the file format says:
Flag (in binary)Meaning
1 nnn nnnn Indicates that there is one data byte to follow that is to be duplicated nnn nnnn (127 maximum) times.
0 nnn nnnn Indicates that there are nnn nnnn bytes of image data to follow (127 bytes maximum) and that there are no duplications.
n 000 0000 End of line field. Indicates the end of a line record. The value of n may be either zero or one. Note that the end of line field is required and that it is reflected in the length of line record field mentioned above.
When reading the file I'm expecting the byte I'm at to return 1 nnn nnnn
where the nnn nnnn
part should be 50.
I've been able to do this using the following:
flag = byte >> 7
numbytes = int(bin(byte)[3:], 2)
But the numbytes calculation feels like a cheap workaround.
Can I do more bit math to accomplish the calculation of numbytes?
How would you approach this?
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