将2个整数转换为十六进制/字节数组? [英] Convert 2 integers to hex/byte array?
问题描述
我正在使用Python通过SPI传输两个整数(范围0 ... 4095).该程序包似乎期望使用[0xff,0xff,0xff]
形式的字节数组.
所以1638(hex:666)和1229(hex:4cd)应该产生[0x66,0x64,0xcd]
.
那么有效的转换会看起来像中间的混合字节一样令人讨厌吗?
I'm using a Python to transmit two integers (range 0...4095) via SPI. The package seems to expect a byte array in form of [0xff,0xff,0xff]
.
So e.g. 1638(hex:666) and 1229(hex:4cd) should yield [0x66,0x64,0xcd]
.
So would an effective conversion look like as the mixed byte in the middle seems quite nasty?
推荐答案
您可以通过左移然后将两个12位值按位进行或"运算,并使用下面显示的int_to_bytes()
函数来完成此操作在Python 2.x中.
You can do it by left shifting and then bitwise OR'ing the two 12-bit values together and using the int_to_bytes()
function shown below, which will work in Python 2.x.
In Python 3, the int
type has a built-in method called to_bytes()
that will do this and more, so in that version you wouldn't need to supply your own.
def int_to_bytes(n, minlen=0):
""" Convert integer to bytearray with optional minimum length.
"""
if n > 0:
arr = []
while n:
n, rem = n >> 8, n & 0xff
arr.append(rem)
b = bytearray(reversed(arr))
elif n == 0:
b = bytearray(b'\x00')
else:
raise ValueError('Only non-negative values supported')
if minlen > 0 and len(b) < minlen: # zero padding needed?
b = (minlen-len(b)) * '\x00' + b
return b
a, b = 1638, 1229 # two 12 bit values
v = a << 12 | b # shift first 12 bits then OR with second
ba = int_to_bytes(v, 3) # convert to array of bytes
print('[{}]'.format(', '.join(hex(b) for b in ba))) # -> [0x66, 0x64, 0xcd]
这篇关于将2个整数转换为十六进制/字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!