Python Forum
Bytes from hex - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Bytes from hex (/thread-15439.html)



Bytes from hex - FredericoFagundes - Jan-17-2019

I need to obtain bytes from hexadecimal digits, and it worked sometimes, I am using:
data=bytes.fromhex('018c5b') #this is just an example
Which gives me b'\x01\x8c['
I realized that some bytes are not correctly converted, like the last one (5b). According to 'https://en.wikiversity.org/wiki/Python_Concepts/Bytes_objects_and_Bytearrays' the byte 20 is interpreted as space, and I think that is what is happening to the 5b, being interpreted as [.

This is from the aforementioned page:
>>> bytes.fromhex( ' 12 20 04 20 E6 20 d5 ' )
b'\x12 \x04 \xe6 \xd5'

Notice that the 20's are ignored and turn into space, but how can I print the 20 or other bytes, like 5b?


RE: Bytes from hex - ichabod801 - Jan-17-2019

That's just how the bytes object prints. If the byte represents a printable character, it prints the printable character. If the byte represents a non-printing character, it print \x and the hex for that byte. I don't know of any way to force it to show every single byte as hex. I think you would have to write your own function to do that.


RE: Bytes from hex - FredericoFagundes - Jan-17-2019

(Jan-17-2019, 03:18 PM)ichabod801 Wrote: That's just how the bytes object prints. If the byte represents a printable character, it prints the printable character. If the byte represents a non-printing character, it print \x and the hex for that byte. I don't know of any way to force it to show every single byte as hex. I think you would have to write your own function to do that.

Thanks a lot! The host that receives the bytes can now understand what they mean. The problem was, once they were in the receiver, I used them as string, not as bytes. Without your answer I wouldn't have seen the problem.