0

In my previous question (Reading serial interface with Python returns distorted data) I asked why data appears distorted because it does not look 16 bytes as expected. Later I found out that the data is actually complete.

But it's still unclear to me why the hexadecimal values are represented as symbols when I struct.pack them, but not like on the picture from the logic analyzer?

enter image description here

>>> struct.pack('f', 1.0)
b'\x00\x00\x80?'
>>> struct.pack('f', 2.0)
b'\x00\x00\x00@'
>>> struct.pack('f', 3.0)
b'\x00\x00@@'
>>> struct.pack('f', 4.0)
b'\x00\x00\x80@'
stardust
  • 343
  • 3
  • 17
  • If the byte value corresponds to a printing character, the string shows that character. Otherwise it shows the hex escape code. – Barmar Mar 11 '20 at 18:11
  • `b'\x00\x00\x80?' == b'\x00\x00\x80\x3f'` because `chr(0x3f)` is `?` – Mark Mar 11 '20 at 18:16
  • @Barmar do you know why is that? It seems to me quite unreasonable, as I am not printing it as string. – stardust Mar 11 '20 at 18:27
  • 1
    @stardust it seems a little confusing in this case, but we often get bytes from networks or files and it's really convenient in those cases when the printable characters are represented as characters rather than hex -- i.e. `b'hello'` vs `b'\0x68\0x65\0x6c\0x6c\0x6f'` – Mark Mar 11 '20 at 18:38
  • 1
    The *purpose* of `struct.pack` is only to convert raw byte values (and other types) into a raw byte string, and printing such a byte array offers a basic translation for the screen only, What you do with that array is totally up to you; if you want to see its contents in hex, then print it out as such. – Jongware Mar 11 '20 at 19:22
  • @usr2564301 I thought it is easier to see directly when you are typing. Well, certainly it is. Thanks! – stardust Mar 11 '20 at 20:09

0 Answers0