字节数组到十六进制字符串

Jam*_*ght 57 python string bytearray python-2.7

我有数据存储在一个字节数组中.如何将此数据转换为十六进制字符串?

我的字节数组示例:

array_alpha = [ 133, 53, 234, 241 ]
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 87

使用str.format:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
Run Code Online (Sandbox Code Playgroud)

或使用 format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Run Code Online (Sandbox Code Playgroud)

注意:在格式语句中,如果需要02,它将填充最多2个前导0.这很重要,因为[0x1, 0x1, 0x1] i.e. (0x010101)它将被格式化为"111"而不是"010101"

或者使用bytearray具有binascii.hexlify:

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
Run Code Online (Sandbox Code Playgroud)

以下是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()
Run Code Online (Sandbox Code Playgroud)

结果:

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
Run Code Online (Sandbox Code Playgroud)

使用方法format做提供额外的格式选项,例如作为用空格分隔的数字" ".join,逗号", ".join,大写印刷"{:02X}".format(x)/ format(x, "02X")等,但在巨大的性能影响成本.

  • @GrijeshChauhan,见[`Built-in Types - Bytes`](http://docs.python.org/3/library/stdtypes.html#bytes). (3认同)
  • @mkingston,你可以省略编码:`b'8535eaf1'.decode()` (2认同)

ori*_*rip 21

考虑十六进制()方法的的bytes关于Python 3.5和至多类型:

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
Run Code Online (Sandbox Code Playgroud)

编辑:它也比hexlify(修改@fattru的基准测试)快得多

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,
))
Run Code Online (Sandbox Code Playgroud)

结果:

bytearray + hexlify -> 0.011218150997592602
byte + hex          -> 0.005952142993919551
Run Code Online (Sandbox Code Playgroud)


kin*_*all 8

hex_string = "".join("%02x" % b for b in array_alpha)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你提供的答案也适用于旧版本的python(这里强制使用2.5.1) (3认同)

ost*_*ach 5

如果您有一个 numpy 数组,则可以执行以下操作:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'
Run Code Online (Sandbox Code Playgroud)

  • 这需要导入外部库,并且没有解决 OP 使用字节这一事实。这不是最可靠的解决方案。 (2认同)