1

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?

2
  • int(7.1746481e-43) works fine so far as I can see. int() rounds towards zero, and 7.1746481e-43 is less than 1. I'm not sure what binary_float_to_int() is doing, but 7.1746481e-43 isn't anywhere close to 512. Commented Jul 30, 2020 at 12:40
  • @brunns the conversion is the 32-bit integer value of the 32-bit IEEE 754 floating point value representing that floating point number. Commented Jul 31, 2020 at 5:32

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.