So I want to turn a positive integer into a little endian byte string of length 2.
Easy! For example, 200
:
>>> b = int.to_bytes(200, 2, 'little')
b'\xc8\x00'
However, as soon as we take one that may be interpreted as some ASCII symbol, like, e.g., 100
:
>>> b = int.to_bytes(100, 2, 'little')
b'd\x00'
>>> print(b) #<< Does not help
b'd\x00'
^Ugly! Barely readable in my opinion! Is there a straight-forward way to tell python to make it hex-style all the way? Like so:
>>> b = int.to_bytes(100, 2, 'little')
b'\x64\x00'
P.S.: For clarification of the question: It is an easy task to write a function that will do just what I want, printing the bytes
as desired, b'\x64\x00'
-style-all-the-way-hex.
The question here is: Is there an option to bring the python interpreter to doing this for me? Like logging.basicConfig(..)
only interpreter.basicNumericFormat(bytes, ..)
. And if so: How would one achieve that?
So I want to turn a positive integer into a little endian byte string of length 2.
Easy! For example, 200
:
>>> b = int.to_bytes(200, 2, 'little')
b'\xc8\x00'
However, as soon as we take one that may be interpreted as some ASCII symbol, like, e.g., 100
:
>>> b = int.to_bytes(100, 2, 'little')
b'd\x00'
>>> print(b) #<< Does not help
b'd\x00'
^Ugly! Barely readable in my opinion! Is there a straight-forward way to tell python to make it hex-style all the way? Like so:
>>> b = int.to_bytes(100, 2, 'little')
b'\x64\x00'
P.S.: For clarification of the question: It is an easy task to write a function that will do just what I want, printing the bytes
as desired, b'\x64\x00'
-style-all-the-way-hex.
The question here is: Is there an option to bring the python interpreter to doing this for me? Like logging.basicConfig(..)
only interpreter.basicNumericFormat(bytes, ..)
. And if so: How would one achieve that?
1 Answer
Reset to default 1If you want the output you gave an example of, you can loop through the bytes and style them in a string. Here's an example:
b = int.to_bytes(100, 2, 'little')
formatted = ''.join(f'\\x{byte:02x}' for byte in b)
print(formatted)
However, if you just want the hex, you can use .hex()
to convert it to a hex.
b = int.to_bytes(100, 2, 'little')
print(b.hex())
.hex()
exists. – Mippy Commented Feb 5 at 13:37hex(1024)==0x400
is scarce a replacement for\x00\x04
! Especially if we are dealing with really large numbers and order is important for the user's reading pleasure! – Markus-Hermann Commented Feb 5 at 13:40b'\x64\x00
, what are you going to do with it? – no comment Commented Feb 5 at 14:22