0

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.

6
  • Possible duplicate of Binary representation of float in Python (bits not hex) Commented Nov 29, 2018 at 12:03
  • The question flagged does not explain how to convert binary back to float. Commented Nov 29, 2018 at 12:09
  • It's not 100% clear what you're looking for here; can you give some example inputs and outputs? (And what's this for? A length-32 string containing '1's and '0's is a really inefficient way of storing data, and I'd be surprised if it's needed for any real-world use.) Commented Nov 29, 2018 at 12:44
  • 1
    Also, are you aware that Python floats are 64 bits (typically IEEE 754 binary64 format, but that's not guaranteed), not 32 bits? Are you starting with a regular Python float, or with something else (e.g., a numpy.float32 object). Commented Nov 29, 2018 at 12:45
  • I want convert it into a bitstring so that I can operate on it for genetic algorithm. Commented Nov 29, 2018 at 12:46

2 Answers 2

6

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”.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd recommend format(value, '032b') over the more complicated bin(value)[2:].zfill(32)
apparently python floats are 64-bit not 32-bit. I also guess that depends on the currently-running cpython implementation. How can you output and input according to the current type of float?
0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.