About to_bytes() method of int type

Question:

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"x00x64" but b"x00d"?

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

Asked By: agongji

||

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: x00x64
text: x00x64
Answered By: furas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.