我有一个浮点值 16.75
需要将其编码为 base64 二进制文件。
我正在使用网站 https://cryptii.com/pipes/binary-to-base64 作为验证的参考。
16.75
编码为 32 位浮点格式,结果为 01000001 10000110 00000000 00000000
,它获取 QYYAAA==
的 Base64 编码值
使用来自 的接受答案一个href="https://stackoverflow.com/questions/40914544/python-base64-float">Python、base64、float 不幸的是,我仍然得到了不同的答案。
xx = base64.encodebytes(struct.pack('<d', 16.75))
print(xx) #b'AAAAAADAMEA=\n'
xx = struct.unpack('<d', base64.decodebytes(xx))
print(xx) #(16.75,)
有人可以指导我哪里出错了吗?
请在评论中发表您的问题 - 我们将尽力尽早回答。
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.
发布评论
评论(1)
您遇到的问题是字节顺序和浮点数大小的差异。
Python 浮点数是双精度数。您输入 Cryptii 网站的二进制文件是 float32 表示形式。
为了匹配您正在查找的答案,您需要使用
"!f"
(big-endian float32) 创建结构,以便让 cryptii 返回您在 python 中使用示例创建的答案,您需要使用
" (little-endian double)将浮点数转换为二进制:
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)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):