简体   繁体   中英

Bytearray conversion, integer is required error on python3

asking for an integer on 0x00 hex position, 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 ). The result of chr(0x00) is a unicode string, however.

You can feed bytearray.extend with either a) a bytes string or b) an iterable of byte-sized integers. Both of these represent "sequence of bytes", which a bytearray is. 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 :

command.append(0x00)

Since a string is an iterable, bytearray.extend tries to append its elements. These are also strings, however. Hence, the error that an integer was expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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