Reputation: 326
Currently I am trying to use pygatt to send data to a ble characteristic but it use a bytearray as argument. My input is a binary file, eg:
$ xxd file.bin
00000000: 0300 1100 0022 0100 0021 8ff6 82ce 8dad ....."...!......
00000010: 54 T
What I want is:
>>> bytearray([0x03, 0x00, 0x11, 0x00, 0x00, 0x22, 0x01, 0x00, 0x00, 0x21, 0x8f, 0xf6, 0x82, 0xce, 0x8d, 0xad, 0x54])
So maybe my comprehension of this low level approach is wrong but here what I do:
import binascii
import hexdump
my_file = "file.bin"
with open(my_file, 'rb') as file_t:
# read the file as xxd do
blob_data = hexdump.hexdump(file_t, result='return')
print(blob_data)
with open(my_file, 'rb') as file_t:
blob_data = binascii.hexlify(file_t.read())
print(blob_data)
with open(my_file, 'rb') as file_t:
blob_data = bytearray(file_t.read())
print(blob_data)
The output is:
00000000: 03 00 11 00 00 22 01 00 00 21 8F F6 82 CE 8D AD ....."...!......
00000010: 54 T
b'030011000022010000218ff682ce8dad54'
bytearray(b'\x03\x00\x11\x00\x00"\x01\x00\x00!\x8f\xf6\x82\xce\x8d\xadT')
But starting this point I am pretty lost on how to convert it to bytearray, the last implementation is not far away but the some characters are converted to their ASCII equivalent (eg \x22 => ")
Anyone have an idea on how to do that ? Thanks guys
Upvotes: 5
Views: 15515
Reputation: 589
Since OP didn't answer their own post, and the issue was resolved in the discussion, I'll recap the answer here.
bytearray([0x03, 0x00, 0x11, 0x00, 0x00, 0x22, 0x01, 0x00, 0x00, 0x21, 0x8f, 0xf6, 0x82, 0xce, 0x8d, 0xad, 0x54])
and
bytearray(b'\x03\x00\x11\x00\x00"\x01\x00\x00!\x8f\xf6\x82\xce\x8d\xadT')
Are the same thing internally. The string representation is different to make the array shorter and more easily readable and it does not affect the actual internal structure of the bytearray.
Any function / program that accepts the first bytearray as a parameter should accept the second one as well. This can be easily verified by comparing the two using the ==
operator.
Upvotes: 5