Get the quot;bitsquot; of a float in Python?(获取“位;Python中的浮点数?)
问题描述
我正在寻找与 Java 的 Float.floatToBits
等效的 Python.
I am looking for the Python equivalent of Java's Float.floatToBits
.
我发现了这个 Python:获取 &操纵(作为整数)浮点数的位模式,但有人知道不那么复杂的方法吗?
I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?
推荐答案
Alex Martelli 在该问题中给出的答案非常简单——您可以将其简化为:
The answer that Alex Martelli gives in that question is really pretty simple -- you can reduce it to:
>>> import struct
>>>
>>>
>>> def floatToBits(f):
... s = struct.pack('>f', f)
... return struct.unpack('>l', s)[0]
...
...
>>> floatToBits(173.3125)
1127043072
>>> hex(_)
'0x432d5000'
一旦你将它作为一个整数,你可以执行任何其他你需要的操作.
Once you have it as an integer, you can perform any other manipulations you need to.
您可以将操作顺序颠倒为往返:
You can reverse the order of operations to round-trip:
>>> def bitsToFloat(b):
... s = struct.pack('>l', b)
... return struct.unpack('>f', s)[0]
>>> bitsToFloat(0x432d5000)
173.3125
这篇关于获取“位";Python中的浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:获取“位";Python中的浮点数?


基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 筛选NumPy数组 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01