Do you have any idea how to encode and decode a float number with base64 in Python. I am trying to use
response='64.000000'
base64.b64decode(response)
Run Code Online (Sandbox Code Playgroud)
the expected output is 'AAAAAAAALkA=' but i do not get any output for float numbers.
Thank you.
Base64 encoding is only defined for byte strings, so you have to convert your number into a sequence of bytes using struct.pack and then base64 encode that. The example you give looks like a base64 encoded little-endian double. So (for Python 2):
>>> import struct
>>> struct.pack('<d', 64.0).encode('base64')
'AAAAAAAAUEA=\n'
Run Code Online (Sandbox Code Playgroud)
For the reverse direction you base64 decode and then unpack it:
>>> struct.unpack('<d', 'AAAAAAAALkA='.decode('base64'))
(15.0,)
Run Code Online (Sandbox Code Playgroud)
So it looks like your example is 15.0 rather than 64.0.
For Python 3 you need to also use the base64 module:
>>> import struct
>>> import base64
>>> base64.encodebytes(struct.pack('<d', 64.0))
b'AAAAAAAAUEA=\n'
>>> struct.unpack('<d', base64.decodebytes(b'AAAAAAAALkA='))
(15.0,)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3261 次 |
| 最近记录: |