Python: How to Convert a Float to Binary (2 Ways)

Updated: June 3, 2023 By: Khue Post a comment

This concise article shows you 2 different ways to convert a float to binary in Python (both of these methods only use built-in features of Python and don’t require any third-party libraries).

Using the struct module

This approach is a two-step process:

  1. Pack the float as a binary string by using the struct.pack() function.
  2. Use the format() function and list comprehension to convert each byte to binary, then join them together.

Code example:

import struct

# your float number
number = 2023.12345

# pack the float as a binary string
s = struct.pack('!f', number) 

# convert each byte to binary and join them
b = ''.join(format(c, '08b') for c in s)




If you have to complete this task many times in the future, you can define a function like this:

def float_to_binary(input: float) -> str:
    return ''.join(format(c, '08b') for c in struct.pack('!f', input))

Using the decimal module

The steps are:

  1. Use the decimal module to convert your float to a decimal object with fixed precision.
  2. Multiply the decimal object by a power of 2 to get an integer.
  3. Convert the result to binary by calling the bin() function.


from decimal import Decimal, getcontext

my_float = 2023.12345

# set the precision to 24 bits
getcontext().prec = 24 

# convert the float to a decimal object
d = Decimal(my_float)

# multiply by 2^23 and convert to integer
i = int(d * (1 << 23)) 

# convert to binary
b = bin(i) 




You can also define a function for reusability:

def float_to_binary(input: float) -> str:
    getcontext().prec = 24
    d = Decimal(input)
    i = int(d * (1 << 23))
    return bin(i)

This tutorial ends here. As said earlier, it is super concise. Happy coding & have a nice day!