14

我正在寻找与 Java 的Float.floatToBits.

我发现了这个Python:获取和操作(作为整数)浮点数的位模式,但有人知道一种不太复杂的方法吗?

4

3 回答 3

29

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
于 2013-01-21T01:09:47.027 回答
3

Here is the 64-bit, little endian representation of a python float1 just to add to the discussion:

>>> import struct
>>> import binascii
>>> print('0x' + binascii.hexlify(struct.pack('<d', 123.456789)))
0x0b0bee073cdd5e40

References:


[1] for example I needed this specifically for interoperability with .NET's BitConverter on intel (ie little endian)

于 2013-12-17T16:35:59.197 回答
1
>>> import ctypes
>>> f = ctypes.c_float(173.3125)
>>> ctypes.c_int.from_address(ctypes.addressof(f)).value
1127043072
于 2019-10-13T10:49:49.143 回答