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

Weird byte conversion in python

I have a function converting integers to bytes and ran into the following issue.

When using the code below.

>>> data = 9

>>> print(data.to_bytes())

I get this :

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

>>> b'\t'

When I should be getting this:

b'\x09'

Can anyone say this is happening?

>Solution :

If you want the hex value, you can use an f-string:

data = 9

print(f"b'\\x{data:02x}'")  # b'\x09'

If you want a hex dump, you can try:

#!/usr/bin/env python3

data = 9
bytes = data.to_bytes(2, 'little')

print(' '.join(f"{byte:02x}" for byte in bytes))  # '09 00'
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