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?
12
votes
so are you asking how to represent a base 16 integer as base 2 in python, or are you asking how to extract certain bits of a number? or both, extract certain bits and display in binary?
- jacoblaw
What's the data type of that message? Please provide a Python literal.
- Stefan Pochmann
2 Answers
28
votes
3
votes
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.