Python Forum
int() function with bytearray() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: int() function with bytearray() (/thread-20961.html)



int() function with bytearray() - Jona66 - Sep-08-2019

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


RE: int() function with bytearray() - ichabod801 - Sep-08-2019

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.