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

2023-12-27

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

我的字节数组的示例:

array_alpha = [ 133, 53, 234, 241 ]

Using str.format http://docs.python.org/2/library/stdtypes#str.format:

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

或使用format http://docs.python.org/2/library/functions.html#format

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

Note:在格式语句中,02意味着它将填充最多 2 个前导0如果需要的话。这很重要,因为[0x1, 0x1, 0x1] i.e. (0x010101)将被格式化为"111"代替"010101"

或使用bytearray http://docs.python.org/2/library/functions.html#bytearray with binascii.hexlify http://docs.python.org/2/library/binascii.html#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()

Result:

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")等等,但代价是极大的性能影响。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

字节数组到十六进制字符串 的相关文章

随机推荐