簡體   English   中英

字節數組到十六進制字符串

[英]Byte Array to Hex String

我將數據存儲在字節數組中。 如何將此數據轉換為十六進制字符串?

我的字節數組示例:

array_alpha = [ 133, 53, 234, 241 ]

使用str.format

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

或使用format

>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1

注意:在格式語句中, 02表示在必要時最多填充 2 個前導0 這很重要,因為[0x1, 0x1, 0x1] ie (0x010101)將被格式化為"111"而不是"010101"

或將bytearraybinascii.hexlify一起binascii.hexlify

>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'

這是 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()

結果:

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

使用format方法確實提供了額外的格式化選項,例如用空格分隔數字" ".join , 逗號", ".join , 大寫打印"{:02X}".format(x) / format(x, "02X")等,但代價是對性能的影響很大。

考慮 Python 3.5 及更高版本上bytes類型的hex() 方法

>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1

編輯:它也比hexlify (上面修改了@falsetru 的基准)

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

結果:

bytearray + hexlify -> 0.011218150997592602
byte + hex          -> 0.005952142993919551
hex_string = "".join("%02x" % b for b in array_alpha)

如果您有一個 numpy 數組,則可以執行以下操作:

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

或者,如果您是函數式編程的粉絲:

>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM