Python 3 struct.pack() printing weird characters

后端 未结 2 1433
梦如初夏
梦如初夏 2021-01-13 18:06

I am testing struct module because I would like to send simple commands with parameters in bytes (char) and unsigned int to another application.

However I found some

2条回答
  •  星月不相逢
    2021-01-13 18:11

    Python is being helpful.

    The bytes representation will use ASCII characters for any bytes that are printable and escape codes for the rest.

    Thus, 0x40 is printed as @, because that's a printable byte. But 0x0a is represented as \n instead, because that is the standard Python escape sequence for a newline character. 0x00 is represented as \x00, a hex escape sequence denoting the NULL byte value. Etc.

    All this is just the Python representation when echoing the values, for your debugging benefit. The actual value itself still consists of actual byte values.

    >>> b'\x40' == b'@'
    True
    >>> b'\x0a' == b'\n'
    True
    

    It's just that any byte in the printable ASCII range will be shown as that ASCII character rather than a \xhh hex escape or dedicated \c one-character escape sequence.

    If you wanted to see only hexadecimal representations, use the binascii.hexlify() function:

    >>> import binascii
    >>> binascii.hexlify(b'@\x00\x00\x00')
    b'40000000'
    >>> binascii.hexlify(b'\n\x00\x00\x00')
    b'0a000000'
    

    which returns bytes as hex characters (with no prefixes), instead. The return value is of course no longer the same value, you now have a bytestring of twice the original length consisting of characters representing hexadecimal values, literal a through to f and 0 through to 9 characters.

提交回复
热议问题