Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What are these symbols in 'bytes' type?

So, I have a single byte in bytes format looking something like that:

b'\xFF'

It is quite easy to understand that a single byte is the two symbols(0-F) after ‘\x’

But sometimes the pattern doesn’t match, containing more than two symbols after ‘\x’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, for example, if I use secrets.token_bytes() I can get something like that:

>>> import secrets
>>> secrets.token_bytes(32)
b't\xbcJ\xf0'

Or, using hashlib module:

>>> import hashlib
>>> hashlib.sha256('abc'.encode()).digest()
b'\xbax\x16\xbf\x8f\x01\xcf\xeaAA@\xde]\xae"#\xb0\x03a\xa3\x96\x17z\x9c\xb4\x10\xffa\xf2\x00\x15\xad'

So, can someone, please, explain what are those additional symbols purpose and how are they generated?
Thanks!

>Solution :

It’s a quirk of the way Python prints byte strings. If the byte value is one of the printable ASCII characters it will print that character; otherwise it prints the hex escape.

Show bytes(range(0x100)) to see it visually.

To get a string that consistently uses hex escapes, you need to build it yourself.

print(''.join(f'\\x{i:02x}' for i in bytes(range(0x100))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading