0

I want to convert a float number to a binary string and back.

I tried this:

import struct
from ast import literal_eval


float_to_binary = bin(struct.unpack('!i',struct.pack('!f', 3.14))[0])
print (float_to_binary)

binary_to_float = float(int(float_to_binary, 0))
print (binary_to_float)


result = float(literal_eval(float_to_binary))
print (result) #wrong, prints 1078523331.0, should be 3.14

1 Answer 1

2

This doesn't do what you think:

binary_to_float = float(int(float_to_binary, 0))

it doesn't reinterpret the data, rather it converts integer to float, e.g. 1234 to 1234.0.

you can use:

>>> from struct import *
>>>
>>> # float -> binary
>>> bin( unpack('I', pack('f', 3.14))[0] )
'0b1000000010010001111010111000011'
>>>
>>>
>>> # binary -> float
>>> unpack('f', pack('I', 0b1000000010010001111010111000011) )[0]
(3.140000104904175,)
>>>
Sign up to request clarification or add additional context in comments.

3 Comments

cool, though when I use variables, like this: original_float = 3.14 binary_string = int(bin( unpack('I', pack('f', original_float))[0] )) float_value = unpack('f', pack('I', binary_string) )[0] doesn't work. ValueError: invalid literal for int() with base 10: '0b1000000010010001111010111000011'
@omgzor You need to tell int that the integer in the string is integer of base 2 using int(..., 2), so it should be binary_string = int(bin( unpack('I', pack('f', original_float))[0] ), 2). You can remove int(bin(...), 2) if you are just interested in the base 10 value, binary_string = unpack('I', pack('f', original_float))[0].
I don't think this works, not exactly. int is 32 bit and float is 64 bit.

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.