转换十六进制后的结果是错误的

2024-09-29 20:17:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python3.6将Hex4991a480转换为float

>>> struct.unpack('!f',bytes.fromhex("4991a480"))
(1193104.0,)

但它不能正常工作。你知道吗

我想得到的结果是1.1931e+06。我使用了一个转换网站,它给出了我所期望的结果。我做错什么了?你知道吗


Tags: bytes网站floatstructunpackfromhexhex4991a480
2条回答

同样,您只需要将它([Python 3]: Format Specification Mini-Language)格式化为指数表示法[Wikipedia]: IEEE 754):

>>> import struct
>>> unpacked = struct.unpack("!f", bytes.fromhex("4991a480"))
>>> unpacked
(1193104.0,)
>>> print("{:e}".format(unpacked[0]))
1.193104e+06

注意,[Python 3]: struct.unpack(format, buffer)返回一个元组。你知道吗

打印的值实际上是您期望的答案,是用长格式符号而不是科学符号书写的。这里没有问题。你知道吗

有关科学记数法的更多信息,请参见this。你知道吗

相关问题 更多 >

    热门问题