Reputation: 13
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
Reputation: 177891
The ctypes
code is:
ctypes.c_float(float_number)
ctypes.c_uint.from_buffer()
.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