Paul Z.
Paul Z.

Reputation: 13

Python binary float to integer conversion using ctypes

Please help me to understand this code snippet:

def binary_float_to_int(float_number: float) -> int:

    return ctypes.c_uint.from_buffer(ctypes.c_float(float_number)).value

The results from these inputs:

print(binary_float_to_int(7.1746481e-43)) 
print(binary_float_to_int(5.3809861e-43))

Are: 512 & 384

Why does the simple Python conversion int(7.1746481e-43) not work? Are there any other ways to do this type of conversion?

Upvotes: 1

Views: 1019

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177891

The ctypes code is:

  1. Put the floating point number in a 32-bit C (IEEE 754-format) ctypes.c_float(float_number)
  2. Treat that same 4-byte value, as an C unsigned int. ctypes.c_uint.from_buffer()
  3. Extract that unsigned integer value .value

Your numbers are correct, if you want the raw 32-bit value of those floating point numbers expressed as integers. Here's another way to do it:

>>> import struct
>>> struct.unpack('i',struct.pack('f',7.1746481e-43))[0]
512
>>> struct.unpack('i',struct.pack('f',5.3809861e-43))[0]
384

These generate the 4-byte float32 value, then unpack it as an integer.

7.1746481e-43 is a very small value close to zero. int() returns the integer portion...in this case, zero, so that's as expected as well.

Upvotes: 2

Related Questions