This is my code, just reading bytes from a file, I want to get the original hexadecimal number but I get some char in the result:
That’s just the default bytes.__str__
rendering of a bytes
object.
When you go:
print(bs)
where bs
is a bytes
object, you get str(bs)
because print()
calls str()
on every argument. That is that same syntax you can use
to define the bytes in Python code, too.
Basicly, this representation aids the eye when looking at bytes data
containing ASCII or Western Europe-ish UTF-8 data, even partially - most
byte values in the ASCII printable range are presented as their glyphs.
You can certainly dump bytes as hexadecimal data. bytes
objects have a
convenience .hex()
method to get it in hexadecimal form:
Example:
>>> b'abc'.hex()
'616263'
>>> help(bytes.hex)
hex(...)
Create a str of hexadecimal numbers from a bytes object.
sep
An optional single character or byte to separate hex bytes.
bytes_per_sep
How many bytes between separators. Positive values count from the
right, negative values count from the left.
Example:
>>> value = b'\xb9\x01\xef'
>>> value.hex()
'b901ef'
>>> value.hex(':')
'b9:01:ef'
>>> value.hex(':', 2)
'b9:01ef'
>>> value.hex(':', -2)
'b901:ef'
So just call .hex()
on the bytes
values you’re trying to print.
The bytes
type is described here:
https://docs.python.org/3/library/stdtypes.html#index-40
Cheers,
Cameron Simpson cs@cskk.id.au
Thank you very much for your kind help