Python: How do I convert from binary to base64 and back?

后端 未结 3 1175
礼貌的吻别
礼貌的吻别 2020-12-19 07:12

Lets say I have some binary value:

0b100

and want to convert it to base64

doing base64.b64decode(0b100) tells me that

3条回答
  •  醉梦人生
    2020-12-19 08:08

    Binary literals are just normal python integers.

    >>> 0b100
    <<< 4
    
    >>> 4
    <<< 4
    

    Just convert to a string and base64 encode it (giving you a string that is the base64 representation of '4'). There is nothing wrong with this approach, it's lossless and simple.

    >>> s = str(0b100).encode('base64')
    
    >>> int(s.decode('base64'))
    <<< 4
    

    If you want, you can use bin to convert the int into a binary string:

    >>> bin(int(s.decode('base64')))
    <<< '0b100'
    

提交回复
热议问题