Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bytes from hex
#1
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?
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  replace bytes with other byte or bytes BigOldArt 1 10,637 Feb-02-2019, 11:00 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020