Show hex value for all bytes, even when ASCII characters are present

后端 未结 2 1474
名媛妹妹
名媛妹妹 2020-12-11 02:30

In Python (3) at least, if a binary value has an ASCII representation, it is shown instead of the hexadecimal value. For instance, the binary value of 67 which

相关标签:
2条回答
  • 2020-12-11 03:04

    There is no specific means of requiring any particular formatting (like \x) for a byte string. If you really need specific formatting, you could use something like the .hex() solution from this question, but wrap it with other code to insert the formatting you need. Another useful tool is the hex builtin function. For instance, if you want \x:

    >>> x = bytes([67, 128])
    >>> print(''.join(r'\x'+hex(letter)[2:] for letter in x))
    \x43\x80
    

    If you just need to be able to visually distinguish the bytes, using hex by itself may work for you (it uses 0x instead of \x):

    >>> print(''.join(hex(letter) for letter in x))
    0x430x80
    

    There is not a way to make this the default behavior for byte strings. Whatever you do, you're going to have to write code that specifies the display format you want; you can't make Python automatically display printable bytes as \x escapes.

    0 讨论(0)
  • 2020-12-11 03:16

    After installing my package all-escapes there will be a new codec available for this usage.

    >>> b = bytes([10,67,128])
    >>> print(b.decode("all-escapes"))
    \x0a\x43\x80
    
    0 讨论(0)
提交回复
热议问题