How can I squeeze four floats into a string?

I would like to represent four floats, for example, 123.545, 56.234, -4534.234, 544.64

using the character set [a..z, A..Z, 0..9] in the shortest possible way so that I can encode the four floats and store them in the filename. What is most effective for this?

I looked at the base64 encoding which doesn't actually compress the result. I also looked at a polyline encoding algorithm that uses characters like )

and {

and I can't seem to do that.

+3


source to share


1 answer


You can use a module struct

to store them as binary 32 bit floats and base64 encode the result. In Python 2:

>>> import struct, base64
>>> base64.urlsafe_b64encode(struct.pack("ffff", 123.545,56.234,-4534.234,544.64))
'Chf3Qp7vYELfsY3F9igIRA=='

      



The == padding can be removed and added to decode such that the base64 string length is a multiple of 4. You will also want to use base64 with URL support to avoid the / character.

+1


source







All Articles