Sohaib Aljey
Sohaib Aljey

Reputation: 35

Converting a float to its IEEE (32 bits) value

I would like to write a script in python that takes a float value for example -37.32 and output its IEEE value (11000010000101010100011110101110). for the first bit if the number is negative than it is 1 else it's 0. for the exponent its the matter of dividing the number by 2 and getting the remainder if I am correct. as for the mantissa, I have no idea how to calculate it. returning a string would be the most reasonable way since it would be better for constructing each element of the IEEE.

can someone help me with the approach I will be taking? or show a script tackling this problem and explaining it to me?

Upvotes: 0

Views: 1020

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308206

The struct module can be used to convert a float to a sequence of bytes. Then it's just a matter of converting each byte to a binary string and joining them together.

>>> import struct
>>> ''.join('{:08b}'.format(b) for b in struct.pack('f', -37.32))
'10101110010001110001010111000010'

Upvotes: 2

Related Questions