[英]How to split 16-bit unsigned integer into array of bytes in python?
I need to split a 16-bit unsigned integer into an array of bytes (ie array.array('B')
) in python. 我需要在Python
array.array('B')
16位无符号整数拆分为字节数组(即array.array('B')
)。
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? 是否有更好/更有效/更Pythonic的方法来完成同一件事?
For non-complex numbers you can use divmod(a, b)
, which returns a tuple of the quotient and remainder of arguments. 对于非复数,可以使用
divmod(a, b)
,它返回商和参数余数的元组。
The following example uses map()
for demonstration purposes. 下面的示例使用
map()
进行演示。 In both examples we're simply telling divmod to return a tuple (a/b, a%b), where a=0xABCD and b=256
. 在两个示例中,我们只是简单地告诉divmod返回一个元组
(a/b, a%b), where a=0xABCD and b=256
。
>>> map(hex, divmod(0xABCD, 1<<8)) # Add a list() call here if your working with python 3.x
['0xab', '0xcd']
# Or if the bit shift notation is distrubing:
>>> map(hex, divmod(0xABCD, 256))
Or you can just place them in the array: 或者,您可以将它们放在数组中:
>>> arr = array.array('B')
>>> arr.extend(divmod(0xABCD, 256))
>>> arr
array('B', [171, 205])
(using python 3 here, there are some nomenclature differences in 2) (在这里使用python 3,在2中有一些术语差异)
Well first, you could just leave everything as bytes
. 首先,您可以将所有内容保留为
bytes
。 This is perfectly valid: 这是完全正确的:
reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)
bytes
allows for "tuple unpacking" (not related to struct.unpack
, tuple unpacking is used all over python). bytes
允许“元组拆包”(与struct.unpack
不相关,元组拆包整个python都使用)。 And bytes
is an array of bytes, which can be accessed via index as you wanted. bytes
是 bytes
数组,可以根据需要通过索引进行访问。
b = struct.pack('<H',0xABCD)
b[0],b[1]
Out[52]: (205, 171)
If you truly wanted to get it into an array.array('B')
, it's still rather easy: 如果您真的想将其放入
array.array('B')
,则仍然很简单:
ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])
print("0x%X" % ary[0])
# 0xCD
You can write your own function like this. 您可以像这样编写自己的函数。
def binarray(i):
while i:
yield i & 0xff
i = i >> 8
print list(binarray(0xABCD))
#[205, 171]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.