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

后端 未结 3 1187
礼貌的吻别
礼貌的吻别 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:10

    How large is your binary value? If it can fit in a single byte, then you can use chr.

    >>> base64.b64encode(chr(255))
    '/w=='
    

    Otherwise I think you'll have to get the individual bytes out of it with some exponential math and arrange them in big-endian or little-endian, calling chr multiple times. (Edit: yan's answer with the struct module is easier :)

    Also, I should note that the binary integer syntax is just that, syntax. The interpreter sees it as just another integer.

    >>> (0b0).__class__
    
    

提交回复
热议问题