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.

1 Answer 1

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.

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.