在Python 3中将二进制文件转换为字节数组

sna*_*man 5 python arrays hex file python-3.x

目前我正在尝试使用pygatt将数据发送到 ble 特征,但它使用 bytearray 作为参数。我的输入是一个二进制文件,例如:

$ xxd file.bin 
00000000: 0300 1100 0022 0100 0021 8ff6 82ce 8dad  ....."...!......
00000010: 54                                       T
Run Code Online (Sandbox Code Playgroud)

我想要的是:

>>> bytearray([0x03, 0x00, 0x11, 0x00, 0x00, 0x22, 0x01, 0x00, 0x00, 0x21, 0x8f, 0xf6, 0x82, 0xce, 0x8d, 0xad, 0x54])
Run Code Online (Sandbox Code Playgroud)

所以也许我对这种低级方法的理解是错误的,但我所做的是:

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)
Run Code Online (Sandbox Code Playgroud)

输出是:

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')
Run Code Online (Sandbox Code Playgroud)

但从这一点开始,我对如何将其转换为字节数组感到非常困惑,最后一个实现并不遥远,但一些字符被转换为它们的 ASCII 等效项(例如 \x22 => ")

有人知道如何做到这一点吗?多谢你们

Ale*_*ter 5

由于OP没有回答他们自己的帖子,并且问题在讨论中得到解决,我将在这里回顾一下答案。

bytearray([0x03, 0x00, 0x11, 0x00, 0x00, 0x22, 0x01, 0x00, 0x00, 0x21, 0x8f, 0xf6, 0x82, 0xce, 0x8d, 0xad, 0x54])
Run Code Online (Sandbox Code Playgroud)

bytearray(b'\x03\x00\x11\x00\x00"\x01\x00\x00!\x8f\xf6\x82\xce\x8d\xadT')
Run Code Online (Sandbox Code Playgroud)

内部都是一样的。字符串表示形式不同是为了使数组更短且更易于阅读,并且不会影响字节数组的实际内部结构。

任何接受第一个字节数组作为参数的函数/程序也应该接受第二个字节数组。通过使用运算符比较两者可以轻松验证这一点==