且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中将十六进制值列表转换为字节数组

更新时间:2022-03-16 06:01:05

可以通过一个简单的单行表达式来解决

That can be solved by a simple one line expression

input = ['0x1', '0x3', '0x2', '0x0', '0x0', '0x10', '0x4', '0x0', '0x0', '0xfa', '0x4']
result = bytes([int(x,0) for x in input])

结果是

b'\x01\x03\x02\x00\x00\x10\x04\x00\x00\xfa\x04'

如果您实际上不想拥有一个字节数组,而是一个整数数组,只需删除 bytes()

If you do not actually want to have a byte array, but an array of integers, just remove the bytes()

result = [int(x,0) for x in input]

结果是

[1, 3, 2, 0, 0, 16, 4, 0, 0, 250, 4]