2

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.

2 Answers2

0

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
  • Ha! @user5173426, yours is a cooler solution. Mine's more readable though. That second version is particularly trippy. –  Feb 19 '19 at 07:10
0
hex2bin_map = {
   "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",
}

print('0b{:016_b}'.format(int('810be320cab3d', 16)))

Shorter version:

print(bin(int('810be320cab3d', 16))[2:])

OUTPUT:

1000000100001011111000110010000011001010101100111101
DirtyBit
  • 16,613
  • 4
  • 34
  • 55