Search code examples
python-3.xutf-8

convert bytes to ascii if possible, hex otherwise


Imagine you have this byte array:

 b = bytes([0x00, 0x78, 0x6f, 0x58, 0x00, 0x4f, 0x30, 0x00]

and you want to print it in a somewhat readable way, using ASCII when possible and hex when not. You could simply use Python's built-in conversion:

>>> b
b'\x00xoX\x00O0\x00'

But that's really not particularly readable. What I'd like is this:

00  x  o  X 00  O  0 00

...that is, a space and the ASCII char if the byte can be printed as ASCII or a two-digit hex value otherwise. I can think of some really awful ways to code this, but there must be a semi-elegant pythonic way. (An array of strings would be great, since you could join() them with a leading space as I've shown above.) How would you do it?


Solution

  • Strings have isprintable and isascii methods which you can use:

    >>> def int2str(i):
    ...     s = chr(i)
    ...     if s.isprintable() and s.isascii():
    ...         return format(s, ">2s")
    ...     return format(i, "02x")
    ... 
    >>> print(' '.join(map(int2str, b)))
    00  x  o  X 00  O  0 00
    >>> print(*map(int2str, b))
    00  x  o  X 00  O  0 00