Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 798
p.sh Avatar asked Jun 30 '26 01:06

p.sh


1 Answers

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,)
like image 121
Duncan Avatar answered Jul 01 '26 19:07

Duncan