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

后端 未结 3 1190
礼貌的吻别
礼貌的吻别 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 07:59

    Depending on how you represent the value 0b100

    >>> import struct
    >>> val = 0b100
    >>> print struct.pack('I', val).encode('base64')
    BAAAAA==
    

    This will turn your value into a 4-byte integer in native endianness, and encode that value into base64. You need to specify the width of your data as base64 is really made for representing binary data in printable characters.

    You can typically encode data as a string of bytes via struct's functions, and then encode into base64. Ensure you're using the same data layout and endianess when decoding.

提交回复
热议问题