Sling Academy
Home/Python/Python: How to Convert a Float to Binary (2 Ways)

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

Last updated: June 03, 2023

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)

print(b)

Output:

01000100111111001110001111110011

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.

Example:

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) 

print(b)

Output:

0b1111110011100011111100110100110101

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!

Next Article: Python: How to get the size of a number (integer, float) in bytes

Previous Article: Python: 2 Ways to Convert an Integer to Binary

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types