Python Forum
bytearray object - why converting to ascii? - 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: bytearray object - why converting to ascii? (/thread-38769.html)



bytearray object - why converting to ascii? - Chepilo - Nov-21-2022

I am a new Python developer.
Albeit new, I come from a C background.

I have a file of bytes I want to read into a bytearray() object. SOME of the byte values are getting converted to an ascii value instead of remaining as a byte value. I must be missing an obvious point.

fh = open(filename, 'rb')
ba = bytearray(fh.read())
fh.close()

Example:

Here are five byte values in the file (I use a Hex editor HxD):
0F 9B 63 69 67

After reading the values into the array, the 0F and 9B are imported fine. However, instead of three separate byte values, 63, 69, and 67, I just have "cig".
Logged Result:
bytearray "\x0f\x9bcig\x00"

This appears to be happening for larger bytes but not always 'decimal appearing' values. 10 and 17 for example, are imported fine.

What can I do to circumvent this problem?
Innovative ideas are welcome!

Thank you sincerely! Big Grin

chepilo


RE: bytearray object - why converting to ascii? - deanhystad - Nov-21-2022

This is not a problem. What you are seeing is an artifact of how bytearray converts the bytes to a string when printing. The thinking is that most user prefer to see bytes displayed as ascii characters, not hex digits. Only non-printable bytes are displayed using hex. The values in the bytearray are unaffected.

If you want to see everything as hex, you need to do that yourself.
b = bytearray(range(127))
print(b)  # Will print some as hex, some as ascii
print("".join([f"\\x{byte:02x}" for byte in b]))  # Converts all to hex format for printing



RE: bytearray object - why converting to ascii? - Chepilo - Nov-21-2022

That's it! Thank you!