Byte Array to Hex String

前端 未结 5 1107
自闭症患者
自闭症患者 2020-12-02 16:30

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 ]
         


        
5条回答
  •  误落风尘
    2020-12-02 16:59

    Consider the hex() method of the bytes type on Python 3.5 and up:

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

    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
    

提交回复
热议问题