4

I have a list of bytes that are represented in string format, for example, when I print the list in Python3.3 I get the following output:

DATA =  ['FF', 'FF', 'FF', 'FF']

I would like to convert these into bytes, for example 0xFF,0xFF,0xFF,0xFF. I have tried the bytearray() function but this returns an error.

I'm guessing that I am missing something simple here, but I have looked around SO and Google and have so far had no luck

Thanks!

Bubo
  • 768
  • 4
  • 18
  • 34

1 Answers1

6

Use binascii.unhexlify() on the joined 'bytes':

import binascii

bytestring = binascii.unhexlify(''.join(DATA))

Demo:

>>> import binascii
>>> DATA =  ['FF', 'FF', 'FF', 'FF']
>>> binascii.unhexlify(''.join(DATA))
b'\xff\xff\xff\xff'

Note that this is way faster than using manual conversion to integers:

>>> import timeit
>>> timeit.timeit("bytes(int(x, 16) for x in DATA)", 'from __main__ import DATA')
1.7035537050105631
>>> timeit.timeit("unhexlify(''.join(DATA))", 'from __main__ import DATA; from binascii import unhexlify')
0.2515432750224136

That's a 7x speed difference.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343