Python printing bytes strangely

Viewed 81

So, I have this very simple code:

from construct import VarInt

a = VarInt.build(12345)
print(a)
with open('hello.txt', 'wb') as file:
    file.write(a)

When I print "a", it shows only the first byte and the last byte for some reason does not show properly. It prints "b'\xb9`'" and it should print "b'\xb9\x60'", or at least that's what I would like to print. Now, when I look at the file that I stored, it saves the bytes exactly how it should with no issue there. Does anybody know what's going on here? Also, with some integers it prints properly, but with this one, for example, does not.

2 Answers

It's not a single byte but

b'\xb9`'

Do You see "`" after 9? It's a character encoded as 0x60. If You want to display all bytes as hexadecimal You can try this snippet:

print(" ".join(hex(n) for n in a))

Why do you think that is does not print properly? Assuming an ASCII derived code page(ASCII, UTF-8 or latin), the code for the back quote (`) is 96 or 0x60.

As \xb9 does not map to a character in your system code page, it is escaped, but as \x60 does map to the back quote, the representation just uses that character.

Related