如何分割的16位无符号整数成蟒蛇的字节数组? [英] How to split 16-bit unsigned integer into array of bytes in python?

查看:152
本文介绍了如何分割的16位无符号整数成蟒蛇的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个16位无符号整数分割成字节数组(即 array.array('B'))的蟒蛇。

I need to split a 16-bit unsigned integer into an array of bytes (i.e. array.array('B')) in python.

例如:

>>> 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)

有没有更好/更高效/更Python完成同样的事情的方法是什么?

Is there a better/more efficient/more pythonic way of accomplishing the same thing?

推荐答案

(使用python 3在这里,也有2一些术语差异)

(using python 3 here, there are some nomenclature differences in 2)

那么首先,你可以只放下一切为字节。这是完全正确的:

Well first, you could just leave everything as bytes. This is perfectly valid:

reg_val_msb, reg_val_lsb = struct.pack('<H', 0xABCD)

字节允许元组拆包(不涉及 struct.unpack ,元组拆包使用全蟒蛇)。和字节的字节数组,可以通过索引你想要进行访问。

bytes allows for "tuple unpacking" (not related to struct.unpack, tuple unpacking is used all over python). And bytes is an array of bytes, which can be accessed via index as you wanted.

b = struct.pack('<H',0xABCD)

b[0],b[1]
Out[52]: (205, 171)

如果你真的想要得到它变成一个 array.array('B'),它仍然是相当容易的:

If you truly wanted to get it into an array.array('B'), it's still rather easy:

ary = array('B',struct.pack('<H',0xABCD))
# ary = array('B', [205, 171])

print("0x%X" % ary[0])
# 0xCD

这篇关于如何分割的16位无符号整数成蟒蛇的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆