About to_bytes() method of int type

Viewed 48

I have a question about to_bytes method of int type in Python.

Say, a = 100.

Why is a.to_bytes(2, "big") not b"\x00\x64" but b"\x00d"?

Seems to me that b"\x00d" is not even 2 bytes.

1 Answers

b"\x00d" means 2 bytes: \x00 and d but for values which are correct char codes (which are "printable") Python displays chars instead of codes. It makes it more readable when it may have readable text.

And chr(0x64) gives d

But if you use .hex() then you can get string 0064, and with .hex(":") you can get 00:64 (but it can't use .hex("\\x"))

If you want only codes \x... then you may have to convert it to string on your own (for example using for-loop and f-string)

a = 100
b = a.to_bytes(2, "big")

print('chr(0x64) :', chr(0x64))
print('b         :', b)
print('b.hex()   :', b.hex())
print('b.hex(":"):', b.hex(':'))

# ------------------------------------

items = []

for value in b:
    items.append( f'\\x{value:02x}' )

text = "".join(items)

print('text:', text)

# shorter
print('text:', "".join(f'\\x{q:02x}' for q in b) )

Result:

chr(0x64) : d
b         : b'\x00d'
b.hex()   : 0064
b.hex(":"): 00:64

text: \x00\x64
text: \x00\x64
Related