Python Forum
bytearray object - why converting to ascii?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
bytearray object - why converting to ascii?
#1
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
Reply
#2
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
Reply
#3
That's it! Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Value error when converting hex value to bytearray shubhamjainj 7 10,569 Mar-20-2023, 05:30 PM
Last Post: Skaperen
  appending to a bytearray Skaperen 21 14,463 Mar-19-2023, 11:05 PM
Last Post: Skaperen
  Split Bytearray into separate Files by Hex delimter lastyle 5 2,680 Mar-09-2023, 07:49 AM
Last Post: bowlofred
  Save multiple Parts of Bytearray to File ? lastyle 1 962 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  Converting data object mbrown009 5 2,779 May-30-2021, 11:35 PM
Last Post: mbrown009
  Bytearray substitution Vismuto 1 2,630 Apr-14-2020, 09:18 AM
Last Post: TomToad
  converting string object inside a list into an intiger bwdu 4 2,633 Mar-31-2020, 10:36 AM
Last Post: buran
  int() function with bytearray() Jona66 1 2,407 Sep-08-2019, 12:41 PM
Last Post: ichabod801
  Conversion needed from bytearray to Floating point braveYug 1 4,130 May-07-2018, 12:23 PM
Last Post: snippsat
  Windows DIB format in bytearray to image? dusca 2 2,773 Mar-28-2018, 10:35 PM
Last Post: dusca

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020