Python Forum

Full Version: int() function with bytearray()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I´m quite a noob and here is my problem with filling up a bytearray with integers (hex):

1. created an empty bytearray

>>> command = bytearray(3)
>>> print(command)
bytearray(b'\x00\x00\x00')
-> everything looks good!

2. added first byte to array

>>> command[0] = int(255)
>>> print(command)
bytearray(b'\xff\x00\x00')
-> everything looks good!

3. added another byte to the array

>>> command[1] = int(33)
>>> print(command)
bytearray(b'\xff!\x00')
-> why is there an "!" in the array??

4. added another byte to the array:
>>> command[1] = int(244)
>>> print(command)
bytearray(b'\xff\xf4\x00')
-> looks fine again!

>>> command[1] = int(132)
>>> print(command)
bytearray(b'\xff\x84\x00')
5. but if I´m adding lower number I´m lost again:

>>> command[1] = int(44)
>>> print(command)
bytearray(b'\xff,\x00')
-> why is there an "," in the bytearray?

Any ideas what is wrong with my approach?

When I´m adding integers between 33 and 126 to a bytearray with the same method I´m getting problems, with even higher integers it works nicely!

kr
jona

Update:

It seems to be a problem with print() function, not with int() to bytearray!

kr
jona
The representation of the bytearray is just the chr() of each byte in the array. So if it's a printable ASCII character, that is displayed, otherwise the hexadecimal for the byte is displayed preceded by \x.