Python how to convert a encoded payload to a list of byte?
Question:
I am actually a beginner of decoding data from sensor.
I got a document of this type
but I dont how to convert 0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303
to a slice of byte like the image above.
I tried to search convert int to bytearray. Since when I apply the 0xB844..
above the python code return it is an integer.
Here is what I have tried so far, but not working:
bytearray.fromhex("0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303")
75802724735341734603890408823112648684683376170384611767809917699.to_bytes(2, 'big')
Answers:
You can use the following code to convert it to a binary string:
import re
num = 0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303
binary = f'{num:0>26b}'
print(binary)
Output:
101110000100010000100110110000110000001100101110001010001100001100000011001010001100001000000010001010001100001000000010001001101100010000000011001001101100001100000010001001101100010000000011001001101100001100000011
Then you can separate these as per your diagram like this:
byte_array = re.findall(r'[01]{8}', binary)
print(byte_array)
Output:
['10111000', '01000100', '00100110', '11000011', '00000011', '00101110', '00101000', '11000011', '00000011', '00101000', '11000010', '00000010', '00101000', '11000010', '00000010', '00100110', '11000100', '00000011', '00100110', '11000011', '00000010', '00100110', '11000100', '00000011', '00100110', '11000011', '00000011']
I am actually a beginner of decoding data from sensor.
I got a document of this type
but I dont how to convert 0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303
to a slice of byte like the image above.
I tried to search convert int to bytearray. Since when I apply the 0xB844..
above the python code return it is an integer.
Here is what I have tried so far, but not working:
bytearray.fromhex("0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303")
75802724735341734603890408823112648684683376170384611767809917699.to_bytes(2, 'big')
You can use the following code to convert it to a binary string:
import re
num = 0xB84426C3032E28C30328C20228C20226C40326C30226C40326C303
binary = f'{num:0>26b}'
print(binary)
Output:
101110000100010000100110110000110000001100101110001010001100001100000011001010001100001000000010001010001100001000000010001001101100010000000011001001101100001100000010001001101100010000000011001001101100001100000011
Then you can separate these as per your diagram like this:
byte_array = re.findall(r'[01]{8}', binary)
print(byte_array)
Output:
['10111000', '01000100', '00100110', '11000011', '00000011', '00101110', '00101000', '11000011', '00000011', '00101000', '11000010', '00000010', '00101000', '11000010', '00000010', '00100110', '11000100', '00000011', '00100110', '11000011', '00000010', '00100110', '11000100', '00000011', '00100110', '11000011', '00000011']