What's the correct way to convert bytes to a hex string in Python 3?

前端 未结 9 1931
一生所求
一生所求 2020-11-22 14:11

What\'s the correct way to convert bytes to a hex string in Python 3?

I see claims of a bytes.hex method, bytes.decode codecs, and have tri

9条回答
  •  醉酒成梦
    2020-11-22 14:55

    The method binascii.hexlify() will convert bytes to a bytes representing the ascii hex string. That means that each byte in the input will get converted to two ascii characters. If you want a true str out then you can .decode("ascii") the result.

    I included an snippet that illustrates it.

    import binascii
    
    with open("addressbook.bin", "rb") as f: # or any binary file like '/bin/ls'
        in_bytes = f.read()
        print(in_bytes) # b'\n\x16\n\x04'
        hex_bytes = binascii.hexlify(in_bytes) 
        print(hex_bytes) # b'0a160a04' which is twice as long as in_bytes
        hex_str = hex_bytes.decode("ascii")
        print(hex_str) # 0a160a04
    

    from the hex string "0a160a04" to can come back to the bytes with binascii.unhexlify("0a160a04") which gives back b'\n\x16\n\x04'

提交回复
热议问题