python - 在 Python 中获取 float 的 "bits"?

标签 python floating-point bitwise-operators

我正在寻找与 Java 的 Float.floatToBits 等效的 Python。

我找到了这个 Python: obtain & manipulate (as integers) bit patterns of floats但是有人知道更简单的方法吗?

最佳答案

Alex Martelli 在该问题中给出的答案非常简单——您可以将其简化为:

>>> import struct
>>> 
>>> 
>>> def floatToBits(f):
...     s = struct.pack('>f', f)
...     return struct.unpack('>l', s)[0]
...     
... 
>>> floatToBits(173.3125)
1127043072
>>> hex(_)
'0x432d5000'

一旦将其作为整数,您就可以执行任何其他需要的操作。

您可以将操作顺序反转为往返:

>>> def bitsToFloat(b):
...     s = struct.pack('>l', b)
...     return struct.unpack('>f', s)[0]

>>> bitsToFloat(0x432d5000)
173.3125

关于python - 在 Python 中获取 float 的 "bits"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14431170/

相关文章:

python Popen : How do I block the execution of grep command until the content to grep is ready?

python - 无法读取肯定存在的文件

python - 使用自定义模型管理器时,Django psycopg2.ProgrammingError 关系不存在

python - Pandas - 图像到 DataFrame

c - Fscanf 没有将文件中的 float 正确读取到链表中

c - 在 C 中将 uint8 拆分为 4 个单元 2,以便稍后获得单元 10

java - Java 中对 Unsigned Int 进行非操作

java - float 的格式

c - Windows 和 Linux 之间通过套接字进行通信的问题

c++ - 在这里进行位移有什么意义?