简体   繁体   English

字节数组转换,python3上的整数是必需的错误

[英]Bytearray conversion, integer is required error on python3

asking for an integer on 0x00 hex position, python3 在0x00十六进制位置要求整数,python3

>>> command = bytearray()
>>> command.extend(chr(0x00))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

Bytearrays consist of either bytes ( b'\\x00' ) or byte-sized int s ( 0x00 ). bytes数组由bytesb'\\x00' )或字节大小的int s( 0x00 )组成。 The result of chr(0x00) is a unicode string, however. 但是, chr(0x00)的结果是一个unicode字符串。

You can feed bytearray.extend with either a) a bytes string or b) an iterable of byte-sized integers. 您可以使用a)字节字符串或b)可迭代的字节大小整数来提供bytearray.extend Both of these represent "sequence of bytes", which a bytearray is. 这两个都代表“字节序列”,即字节bytearray Also, both can be used with hex notation. 同样,两者都可以使用十六进制表示法。

command.extend(b'\x00')
command.extend([0x00])

In case you want to add a single integer, you can also use bytearray.append : 如果要添加一个整数,也可以使用bytearray.append

command.append(0x00)

Since a string is an iterable, bytearray.extend tries to append its elements. 由于字符串是可迭代的,因此bytearray.extend尝试附加其元素。 These are also strings, however. 但是,这些也是字符串。 Hence, the error that an integer was expected. 因此,出现了预期为整数的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM