17

I am looking for the Python equivalent of Java's Float.floatToBits.

I found this Python: obtain & manipulate (as integers) bit patterns of floats but does anyone know of a less complicated way?

1
  • 2
    Also how would I do the opposite: Float.BitsToFloat? Commented Jan 21, 2013 at 1:23

3 Answers 3

34

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
Sign up to request clarification or add additional context in comments.

9 Comments

I'm not seeing the need for enforcing big-endian. Any problem with using '=' instead ?
Thanks. Also how would I do the opposite: Float.BitsToFloat?
I wouldn't depend on that assertion working too often. Try it with startVal = 123.456.
Yeah, good point, and I like to yell at people about equality testing on floats. I'll remove it.
I like it, but is there anything that doesn't involve string conversions? I've often found via profiling that strings are what code takes the most time operating on.
|
4

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)

Comments

4
>>> import ctypes
>>> f = ctypes.c_float(173.3125)
>>> ctypes.c_int.from_address(ctypes.addressof(f)).value
1127043072

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.