Print Hex With Spaces Between
In Python 3.8+, hex
function has an optional argument splitter.
>>> print(b'\xff\x00\xff\xff\xff'.hex(' '))
'ff 00 ff ff ff'
And you can split the hex string with any character you want.
>>> print(b'\xff\x00\xff\xff\xff'.hex(':'))
'ff:00:ff:ff:ff'
You can convert to a string:
bytestring = str(b'\xff\x00\xff\xff\xff').encode('hex')
print(bytestring)
#ff00ffffff
Then iterate over it in chunks of 2, and join the chunks with a space:
print(" ".join([bytestring[i:i+2] for i in range(0, len(bytestring), 2)]))
#'ff 00 ff ff ff'
just convert your array of bytes to hex strings, and join the result with space:
>>> d=b'\xff\x00\xff\xff\xff'
>>> " ".join(["{:02x}".format(x) for x in d])
'ff 00 ff ff ff'
note that " ".join("{:02x}".format(x) for x in d)
would also work, but forcing the list creation is faster as explained here: Joining strings. Generator or list comprehension?
In python 2, bytes
is str
so you have to use ord
to get character code
>>> " ".join(["{:02x}".format(ord(x)) for x in d])