Reputation: 13690
I want to convert a list of bytes as a string of hex values. The list of bytes is a bit long, so I want spaces between the bytes to improve readability. The function hexlify
as well as hex
does the job:
import binascii
a = [1,2,3,4]
s = binascii.hexlify(bytearray(a))
print s
s = bytes(a).hex()
print s
But the result is '01020304'. I want a dump with a space between the bytes like '01 02 03 04'. How can I do this in an efficient way?
Edit: There is also a way to iterate all bytes. Would this be efficient?
s = ' '.join('%02x' % i for i in a)
Upvotes: 0
Views: 3350
Reputation: 55589
You can use bytes.hex with a separator string:
>>> bs = b'Hello world'
>>> bs.hex(sep=' ')
'48 65 6c 6c 6f 20 77 6f 72 6c 64'
Upvotes: 3
Reputation: 11
You can iterate the result
import binascii
a = [1,2,3,4]
s = binascii.hexlify(bytearray(a))
s = bytes(a).hex()
iterate = iter(s)
print ' '.join(a+b for a,b in zip(iterate, iterate))
Upvotes: 1