1
>>> bytearray([2,88])
bytearray(b'\x02X')

Why is bytearray() combining them? And why is it turning 88 into ascii (X)? I was expecting two separate values, and 88 to convert to hex (x58)

bytearray(b'\x02,x58)

1 Answer 1

1

Because ASCII 88 (capital letter X) is printable, and the behavior of bytes.str() / bytes.repr() is to not encode printable characters.

Just try to print bytearray(range(256)) and you'll see that there is a range of printable characters (from \x20 to \x7e) which do not get displayed as \x##.

Nonetheless, you can input \x58 in a byte sequence, but it will again be displayed as X:

>>> b'\x58'
b'X'

Here's a little trick to print all values encoded to \x## form:

>>> b = bytearray([2,88])
>>> print(''.join('\\x%02x'%x for x in b))
\x02\x58
Sign up to request clarification or add additional context in comments.

1 Comment

Ah okay, thanks. So is there a way to take an array: arr = [2,88] and have it turn into: bytearray(b'\x02,x58) using bytearray somehow?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.