0

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)
harper
  • 13,345
  • 8
  • 56
  • 105
  • This should help: https://stackoverflow.com/a/9475354/1174966 – jdaz Sep 05 '20 at 09:44
  • @jdaz That answer generates a list of strings. I want to get one string that can be processed further, e.g. written to a file. – harper Sep 05 '20 at 09:50
  • What version of python are you using? There is a `sep` argument to `bytes.hex` but it is new in 3.8. – alani Sep 05 '20 at 10:27

2 Answers2

2

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'
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
1

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))