如何在python中将十六进制值列表转换为字节数组 [英] How to convert list of hex values into a byte array in python
本文介绍了如何在python中将十六进制值列表转换为字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的十六进制列表['0x1','0x3','0x2','0x0','0x0','0x10','0x4','0x0','0x0','0xfa','0x4']
i have hex list like this ['0x1', '0x3', '0x2', '0x0', '0x0', '0x10', '0x4', '0x0', '0x0', '0xfa', '0x4']
我打算通过USB发送它,所以我需要转换为字节数组,python中有可用的方法吗?
and i intend to send it over USB, so i need to convert into a bytearray, is there a way available in python?
推荐答案
可以通过一个简单的单行表达式来解决
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]
这篇关于如何在python中将十六进制值列表转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文