I'm trying to convert an int (i.e. 3490) into 2 bytes via the to_bytes() function and instead of returning b'\x0d\xa2', I'm getting b'\r\xa2'. What am I missing here and how can I get the former to return?
python to_bytes() to return an even number of digits
43 Views Asked by tehawtness At
2
There are 2 best solutions below
0
On
When You Print the value python represents it in a string thus in ASCII, \x0d (which represents the byte with hexadecimal value 0x0d) is represented as \r, because in ASCII encoding, the byte 0x0d corresponds to the carriage return character (i.e. '\r').
If You Want to See the Hex representation just call .hex():
num = 3490
result_bytes = num.to_bytes(2, byteorder='big')
print(result_bytes.hex())
The two expressions are equivalent, as
ord('\r') == 0x0d. In other words,b'\x0d\xa2' == b'\r\xa2'.If you're looking for how to get a even-sized hex string for bytes, you may try