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

前端 未结 2 605
南笙
南笙 2020-12-15 09:17

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

相关标签:
2条回答
  • 2020-12-15 10:04

    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)
    
    0 讨论(0)
  • 2020-12-15 10:15

    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.

    0 讨论(0)
提交回复
热议问题