mercury
mercury

Reputation: 195

Display bytearray in a neat readable hex format

If I have a byte array

aaa=b'\x02\xc0\x00\x48\x04'

and I want to display it in hex, it will display the bytes as

b'\x02\xc0\x00H\x04'

which is a mixture of hex and ASCII characters. It is not neat to read when the array is too large.

The command I use is

print(' '.join(hex(n) for n in aaa))

The output is

0x2 0xc0 0x0 0x48 0x4

This is still different from my ideal representation:

02 C0 00 48 04

How can I achieve that?

Upvotes: 1

Views: 466

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114440

You can format the strings:

' '.join(f'{:02X}' for n in aaa)

Upvotes: 0

mercury
mercury

Reputation: 195

Thanks to @furas. The solution is

aaa.hex(' ').upper()

The result will be

'02 C0 00 48 04'

Upvotes: 1

Related Questions