Python3 Convert list of HEX values to Bytes
Question: 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!


Answer: Use
[`binascii.unhexlify()`](https://docs.python.org/3/library/binascii.html#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.

