1

How to get the 32 bit float representation of a string as binary IEEE 754?

Example

'00111111100000000000000000000000' -> 1.00

This question is the reverse of: Binary representation of float in Python (bits not hex) and I couldn't find the answer elsewhere. Please note that I am very new to coding so please be gentle.

Community
  • 1
  • 1
Perm. Questiin
  • 429
  • 2
  • 9
  • 21

1 Answers1

3

Using struct.pack and struct.unpack:

>>> import struct
>>> n = '00111111100000000000000000000000'
>>> struct.unpack('f', struct.pack('i', int(n, 2)))[0]
1.0
  • int(.., 2) to convert the binary representation to int (base 2)
  • struct.pack('i', ..) to convert bytes (i: 32bit int)
  • struct.unpack('f', ...)[0] to convert bytes back to float.

For other struct format character, see Format charactes - struct module documentation.

falsetru
  • 357,413
  • 63
  • 732
  • 636