Convert 2 Integers To Hex/byte Array?
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)
Solution 1:
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.
defint_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 > 0andlen(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 bytesprint('[{}]'.format(', '.join(hex(b) for b in ba))) # -> [0x66, 0x64, 0xcd]
Post a Comment for "Convert 2 Integers To Hex/byte Array?"