I need to split a 16-bit unsigned integer into an array of bytes (i.e. array.array('B')
) in python.
For example:
>>> reg_val = 0xABCD
[insert python magic here]
>>> print("0x%X" % myarray[0])
0xCD
>>> print("0x%X" % myarray[1])
0xAB
The way I'm currently doing it seems very complicated for something so simple:
>>> import struct
>>> import array
>>> reg_val = 0xABCD
>>> reg_val_msb, reg_val_lsb = struct.unpack("<BB", struct.pack("<H", (0xFFFF & reg_val)))
>>> myarray = array.array('B')
>>> myarray.append(reg_val_msb)
>>> myarray.append(reg_val_lsb)
Is there a better/more efficient/more pythonic way of accomplishing the same thing?
(using python 3 here, there are some nomenclature differences in 2)
Well first, you could just leave everything as
bytes
. This is perfectly valid:bytes
allows for "tuple unpacking" (not related tostruct.unpack
, tuple unpacking is used all over python). Andbytes
is an array of bytes, which can be accessed via index as you wanted.If you truly wanted to get it into an
array.array('B')
, it's still rather easy:For non-complex numbers you can use
divmod(a, b)
, which returns a tuple of the quotient and remainder of arguments.The following example uses
map()
for demonstration purposes. In both examples we're simply telling divmod to return a tuple(a/b, a%b), where a=0xABCD and b=256
.Or you can just place them in the array:
You can write your own function like this.