Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I extract specific bits from a byte?

I have a message which reads as 14 09 00 79 3d 00 23 27. I can extract each byte from this message by calling message[4], which will give me 3d for example. How do I extract the individual 8 bits from this byte? For example, how would I get bits 24-27 as as single message? How about just bit 28?

like image 225
Aditya Salapaka Avatar asked Jul 20 '17 17:07

Aditya Salapaka


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 access specific bits?

For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.

How do you get the bits of a binary number in Python?

To find necessary bits to represent a number – we use "bit_length()" method of "int" class, it is called with an integer object and returns the total number of bits to require to store/represent an integer number in binary. Note: If the value is 0, bit_length() method returns 0.


2 Answers

To answer the second part of your question, you can get specific bit values using bitwise operations

# getting your message as int
i = int("140900793d002327", 16)

# getting bit at position 28 (counting from 0 from right)
(i >> 28) & 1

# getting bits at position 24-27
bin((i >> 24) & 0b111)
like image 196
Anis Avatar answered Oct 22 '22 14:10

Anis


The easiest way to do this is to use the & operator. Convert your message to an int using int(str_msg, 16). convert int to binary string using bin(myint)

To get bits 4-6 (from left) in a byte:

>> msg = int("10110111", 2) # or 0b10110111
>> extractor = int("00011100", 2) # or 0b10110111
>> result = msg & extractor
>> print bin(result)
00010100

If you want, you can bit shift result using result >> 2. Obviously you will want to make this more dynamic but this is a dumbed down example.

like image 45
Ian Kirkpatrick Avatar answered Oct 22 '22 16:10

Ian Kirkpatrick