user1150764
user1150764

Reputation: 103

Converting a 32-bit int value into a float

I have a program that reads from a file that grabs 4 bytes from that file. The below hex should be 0.5 in float:

00 00 00 3F

I currently have a method that displays integer values and would like to convert the integer from 1056964608 to 0.5. This should also be able to handle negative float numbers. Can someone explain to me how this can be done in Python 2.6?

Upvotes: 1

Views: 3306

Answers (1)

user149341
user149341

Reputation:

Using the struct module:

>>> struct.unpack("<f", "\x00\x00\x00\x3f")
(0.5,)

If you really need to convert from the integer, rather than just from the bytes, you can do that too:

>>> struct.unpack("<f", struct.pack("<I", 1056964608))
(0.5,)

Upvotes: 9

Related Questions