Search code examples
pythoniotsensorspayload

Handling of byte data after converting it to bits in Python


Could somebody help me with converting 7 byte of data into binary value in Python?

The server receives a 7 byte data using MQTT and I want to convert this data into binary, break it down and extract specific lengths of bits from this data in Python for further handling.

If I received:

810be320cab3d

I want to convert it to:

1000000100001011111000110010000011001010101100111101

store this in a variable, then later break this value down into a couple of piece so I can slice the value using str() or truncate(), I hope.


Solution

  • Here's a simple way:

    data = '810be320cab3d'
    
    bits = { '0':'0000', '1':'0001', '2':'0010', '3':'0011'
             '4':'0100', '5':'0101', '6':'0110', '7':'0111',
             '8':'1000', '9':'1001', 'a':'1010', 'b':'1011',
             'c':'1100', 'd':'1101', 'e':'1110', 'f':'1111' }
    
    def main():
        r = ""
        for c in data:
            r += bits[c]
        print r
    
    main()
    

    Output:

    1000000100001011111000110010000011001010101100111101