Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Extracting bits from a byte

Tags:

python

byte

bit

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?

like image 906
Evan Borgstrom Avatar asked Mar 30 '12 15:03

Evan Borgstrom


People also ask

How do I extract a bit in Python?

*/ Step 1 : first convert the number into its binary form using bin(). Step 2 : remove the first two character. Step 3 : then extracting k bits from starting position pos from right.so, the ending index of the extracting substring is e=len(bi)-pos and starting index=e-k+1 Step 4 : extract k bit sub-string.

How do I extract a bit from an integer?

printf("int has %ud bits\n", sizeof(int) * 8); sizeof() returns the size in bytes of an integer, and then you multiply that result by 8 (bits per byte in 99.999% of cases)to get the size in bits of your integer, and therefore the size of the masks you have to apply.

How many bits is a byte Python?

Note that 1 byte equals 8 bits. Therefore, you can think that Python uses 24 bytes as an overhead for storing an integer object. It returns 28 bytes. Since 24 bytes is an overhead, Python uses 4 bytes to represent the number 100.


1 Answers

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 
like image 198
Zaur Nasibov Avatar answered Sep 21 '22 17:09

Zaur Nasibov