p.sh
p.sh

Reputation: 67

Python, base64, float

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)

the expected output is 'AAAAAAAALkA=' but i do not get any output for float numbers.

Thank you.

Upvotes: 3

Views: 5999

Answers (1)

Duncan
Duncan

Reputation: 95712

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'

For the reverse direction you base64 decode and then unpack it:

>>> struct.unpack('<d', 'AAAAAAAALkA='.decode('base64'))
(15.0,)

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,)

Upvotes: 7

Related Questions