Hex to Base64 conversion in Python

前端 未结 7 1038
一整个雨季
一整个雨季 2021-02-04 03:47

I want to convert a simple HEX string such as 10000000000002ae to Base 64.

The hex string is to be converted to bytes, and the bytes are then encoded to base64 notation,

相关标签:
7条回答
  • 2021-02-04 04:20

    The tool you link to simply interprets the hex as bytes, then encodes those bytes to Base64.

    Either use the binascii.unhexlify() function to convert from a hex string to bytes, or use the bytes.fromhex() class method. Then use the binascii.b2a_base64() function to convert that to Base64:

    from binascii import unhexlify, b2a_base64
    
    result = b2a_base64(unhexlify(hex_string))
    

    or

    from binascii import b2a_base64
    
    result = b2a_base64(bytes.fromhex(hex_string))
    

    In Python 2, you can also use the str.decode() and str.encode() methods to achieve the same:

    result = hex_string.decode('hex').encode('base64')
    

    In Python 3, you'd have to use the codecs.encode() function for this.

    Demo in Python 3:

    >>> bytes.fromhex('10000000000002ae')
    b'\x10\x00\x00\x00\x00\x00\x02\xae'
    >>> from binascii import unhexlify, b2a_base64
    >>> unhexlify('10000000000002ae')
    b'\x10\x00\x00\x00\x00\x00\x02\xae'
    >>> b2a_base64(bytes.fromhex('10000000000002ae'))
    b'EAAAAAAAAq4=\n'
    >>> b2a_base64(unhexlify('10000000000002ae'))
    b'EAAAAAAAAq4=\n'
    

    Demo on Python 2.7:

    >>> '10000000000002ae'.decode('hex')
    '\x10\x00\x00\x00\x00\x00\x02\xae'
    >>> '10000000000002ae'.decode('hex').encode('base64')
    'EAAAAAAAAq4=\n'
    >>> from binascii import unhexlify, b2a_base64
    >>> unhexlify('10000000000002ae')
    '\x10\x00\x00\x00\x00\x00\x02\xae'
    >>> b2a_base64(unhexlify('10000000000002ae'))
    'EAAAAAAAAq4=\n'
    
    0 讨论(0)
提交回复
热议问题