Matriz de Bytes a Cadena hexadecimal
Tengo datos almacenados en una matriz de bytes. ¿Cómo puedo convertir estos datos en una cadena hexadecimal?
Ejemplo de mi matriz de bytes:
array_alpha = [ 133, 53, 234, 241 ]
5 answers
Utilizando str.format
:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
O utilizando format
>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Nota: En las declaraciones de formato, el
02
significa que se rellenará con hasta 20
s iniciales si es necesario. Esto es importante ya que[0x1, 0x1, 0x1] i.e. (0x010101)
tendría el formato"111"
en lugar de"010101"
O el uso de bytearray
con binascii.hexlify
:
>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
Aquí hay un punto de referencia de los métodos anteriores en Python 3.6.1:
from timeit import timeit
import binascii
number = 10000
def using_str_format() -> str:
return "".join("{:02x}".format(x) for x in test_obj)
def using_format() -> str:
return "".join(format(x, "02x") for x in test_obj)
def using_hexlify() -> str:
return binascii.hexlify(bytearray(test_obj)).decode('ascii')
def do_test():
print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
if using_str_format() != using_format() != using_hexlify():
raise RuntimeError("Results are not the same")
print("Using str.format -> " + str(timeit(using_str_format, number=number)))
print("Using format -> " + str(timeit(using_format, number=number)))
print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))
test_obj = bytes([i for i in range(255)])
do_test()
test_obj = bytearray([i for i in range(255)])
do_test()
Resultado:
Testing with 255-byte bytes:
Using str.format -> 1.459474583090427
Using format -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format -> 1.443447684109402
Using format -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684
Los métodos que usan format
proporcionan opciones de formato adicionales, como por ejemplo separar números con espacios " ".join
, comas ", ".join
, impresión en mayúsculas"{:02X}".format(x)
/format(x, "02X")
, etc., pero a un costo de gran impacto en el rendimiento.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-06 06:30:44
Considere el método hex () del tipo bytes
en Python 3.5 y arriba:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDITAR: también es mucho más rápido que hexlify
(modificado los puntos de referencia de @ falsetru arriba)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Resultado:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-06 09:58:41
hex_string = "".join("%02x" % b for b in array_alpha)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-06 15:27:07
Si tienes una matriz numpy, puedes hacer lo siguiente:
>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-06 17:55:28
O, si eres fan de la programación funcional:
>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-06 15:28:03