Hex to Base64 conversion in Python

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

    Edit 26 Aug 2020: As suggested by Ali in the comments, using codecs.encode(b, "base64") would result in extra line breaks for MIME syntax. Only use this method if you do want those line breaks formatting.

    For a plain Base64 encoding/decoding, use base64.b64encode and base64.b64decode. See the answer from Ali for details.


    In Python 3, arbitrary encodings including Hex and Base64 has been moved to codecs module. To get a Base64 str from a hex str:

    import codecs
    
    hex = "10000000000002ae"
    b64 = codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode()
    

提交回复
热议问题