user8210645
user8210645

Reputation:

Float to Binary and Binary to Float in Python

Can anyone tell me how to convert a float number to 32-bit binary string and from a 32-bit binary string to a float number in python?

'bin' function in python works only for integers.

I need a single bit string as in internal representation. I do not want separate bit strings for the number before and after the decimal places joined by a decimal place in between.

EDIT: The question flagged does not explain how to convert binary string to float back.

Upvotes: 0

Views: 13396

Answers (2)

Adan Mori
Adan Mori

Reputation: 11

I was able to create a program that takes bin decimals as string an returns int decimals! I used a for loop to start from 1 until the len() of the str+1 to use i number to elevate 2 and, then just keep track of the result with result +=:

def binary_poin_to_number(bin1)->float:
    #Try out string slicing here, later
    result = 0
    for i in range(1,len(bin1)+1):
        if bin1[i-1] == '1':
            result += 2**-i
    return result 

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 223454

Copied from this answer and edited per suggestion from Mark Dickinson:

import struct

def float_to_bin(num):
    return format(struct.unpack('!I', struct.pack('!f', num))[0], '032b')

def bin_to_float(binary):
    return struct.unpack('!f',struct.pack('!I', int(binary, 2)))[0]

print float_to_bin(3.14) yields “01000000010010001111010111000011”.

print bin_to_float("11000000001011010111000010100100") yields “-2.71000003815”.

Upvotes: 6

Related Questions