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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19210414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:09:10  来源:igfitidea点击:

Byte Array to Hex String

pythonstringpython-2.7bytearray

提问by Jamie Wright

I have data stored in a byte array. How can I convert this data into a hex string?

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

Example of my byte array:

我的字节数组示例:

array_alpha = [ 133, 53, 234, 241 ]

采纳答案by falsetru

Using str.format:

使用str.format

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

or using format

或使用 format

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

Note:In the format statements, the 02means it will pad with up to 2 leading 0s if necessary. This is important since [0x1, 0x1, 0x1] i.e. (0x010101)would be formatted to "111"instead of "010101"

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

or using bytearraywith binascii.hexlify:

或者使用bytearray具有binascii.hexlify

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


Here is a benchmark of above methods in Python 3.6.1:

这是 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

Methods using formatdo provide additional formatting options, as example separating numbers with spaces " ".join, commas ", ".join, upper-case printing "{:02X}".format(x)/format(x, "02X"), etc., but at a cost of great performance impact.

使用的方法format确实提供了额外的格式化选项,例如用空格" ".join、逗号", ".join、大写打印"{:02X}".format(x)/format(x, "02X")等分隔数字,但代价是对性能的影响很大。

回答by kindall

hex_string = "".join("%02x" % b for b in array_alpha)

回答by kindall

Or, if you are a fan of functional programming:

或者,如果您是函数式编程的粉丝:

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

回答by ostrokach

If you have a numpy array, you can do the following:

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

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

回答by orip

Consider the hex() methodof the bytestype on Python 3.5 and up:

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

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

EDIT: it's also much faster than hexlify(modified @falsetru's benchmarks above)

编辑:它也比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,
))

Result:

结果:

bytearray + hexlify -> 0.011218150997592602
byte + hex          -> 0.005952142993919551