Reputation: 429
I have a float value 16.75
which needs to be encoded into base64 binary.
I am using the website https://cryptii.com/pipes/binary-to-base64 as a reference for validation.
16.75
encoded into 32bit floating point format results in 01000001 10000110 00000000 00000000
which gets a base64 encoding value of QYYAAA==
Using the accepted answer from Python, base64, float unfortunately leads me to a different answer still.
xx = base64.encodebytes(struct.pack('<d', 16.75))
print(xx) #b'AAAAAADAMEA=\n'
xx = struct.unpack('<d', base64.decodebytes(xx))
print(xx) #(16.75,)
Can someone guide me where am I going wrong? Do post your questions in comments - will try to answer as early as possible.
Upvotes: 1
Views: 870
Reputation: 4572
The problem you're running into is the differences in byte order and size of float.
Python floats are doubles. The binary you're feeding into the Cryptii website is a float32 representation.
To match the answer you were looking up, you'd need to create the struct using "!f"
(big-endian float32)
a = base64.encodebytes(struct.pack('!f', 16.75))
print(a) # b'QYYAAA==\n'
To get cryptii to return the answer you were creating in python with your example, you'd need to convert the float to binary using "<d"
(little-endian double):
print(''.join('{:0>8b}'.format(c) for c in struct.pack('<d', 16.75)))
0000000000000000000000000000000000000000110000000011000001000000
Upvotes: 2