Hex to Base64 conversion in Python

前端 未结 7 1015
一整个雨季
一整个雨季 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:10

    from base64 import b64encode, b64decode
    
    # hex -> base64
    s = 'cafebabe'
    b64 = b64encode(bytes.fromhex(s)).decode()
    print('cafebabe in base64:', b64)
    
    # base64 -> hex
    s2 = b64decode(b64.encode()).hex()
    print('yv66vg== in hex is:', s2)
    assert s == s2
    

    This prints:

    cafebabe in base64: yv66vg==
    yv66vg== in hex is: cafebabe
    

    The relevant functions in the documentation, hex to base64:

    • b64encode
    • bytes.fromhex
    • bytes.decode

    Base64 to hex:

    • b64decode
    • str.encode
    • bytes.hex

    I don't understand why many of the other answers are making it so complicated. For example the most upvoted answer as of Aug 26, 2020:

    • There is no need for the codecs module here.
    • The codecs module uses base64.encodebytes(s) under the hood (see reference here), so it converts to multiline MIME base64, so you get a new line after every 76 bytes of output. Unless you are sending it in e-mail, it is most likely not what you want.

    As for specifying 'utf-8' when encoding a string, or decoding bytes: It adds unnecessary noise. Python 3 uses utf-8 encoding for strings by default. It is not a coincidence that the writers of the standard library made the default encoding of the encode/decode methods also utf-8, so that you don't have to needlessly specify the utf-8 encoding over and over again.

提交回复
热议问题