Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to convert floating to binary
A floating-point number is a number that has a decimal point and can represent both large and very small values. Binary representation uses only 0's and 1's in the base-2 numeral system.
Converting floating-point numbers to binary in Python requires representing them in the IEEE 754 format (a standard for numerical representation using 1 bit for sign, 8 bits for exponent, and 23 bits for significand in 32-bit format). For example, the floating number 9.87 has the IEEE 754 32-bit binary representation "01000001000111011110101110000101".
In this article, we will discuss different ways to convert floating-point numbers to binary using Python.
Using struct Module
The struct module converts between Python values and C-style binary data. It converts floating-point numbers to binary by packing them into IEEE 754 format using struct.pack() and interpreting the result as an integer using struct.unpack().
Example
The following example uses the struct module to convert a floating-point number to binary format ?
import struct
n = 9.87
output = struct.unpack('!I', struct.pack('!f', n))[0]
print(f"{output:032b}")
# 032b formats output as a 32-bit binary string
The output of the above code is ?
01000001000111011110101110000101
Note: The !f packs a float as 32-bit big-endian and !I unpacks those 4 bytes as a 32-bit big-endian unsigned integer.
Using NumPy
NumPy is an open-source Python library that supports multi-dimensional arrays and provides mathematical functions for array operations.
NumPy converts floating-point numbers to binary using the following methods ?
- np.float32() − Creates a single-precision (32-bit) floating-point number
- np.view() − Interprets the memory of a floating-point number as an integer
- bin() − Built-in function to get binary representation
Example
The following example uses NumPy to convert a floating-point number to binary representation ?
import numpy as np # Example floating-point number n = 9.87 float_array = np.float32(n) int_repr = float_array.view(np.int32) # Convert to binary string output = bin(int_repr) print(output)
The output of the above code is ?
0b1000001000111011110101110000101
Using Manual IEEE 754 Implementation
This method manually extracts the sign, exponent, and mantissa of the floating-point number to create the IEEE 754 binary representation.
Example
The following example extracts the sign bit, splits the number into integer and fractional parts, and converts each part to binary ?
n = 9.87
# If n is greater than 0, sign is assigned as 0 else as 1
sign = '0' if n >= 0 else '1'
n = abs(n)
# Getting integer and fractional parts
int_part = int(n)
frac_part = n - int_part
# Convert integer part to binary
int_bin = bin(int_part)[2:]
# Convert fractional part to binary
frac_bin = []
while frac_part and len(frac_bin) < 23:
frac_part *= 2
bit = int(frac_part)
frac_bin.append(str(bit))
frac_part -= bit
# Normalize
exponent = len(int_bin) - 1
mantissa = int_bin[1:] + ''.join(frac_bin)
# Adjust mantissa to 23 bits
mantissa = (mantissa + '0' * 23)[:23]
# Exponent with bias (127)
exponent_bin = f"{exponent + 127:08b}"
# IEEE 754 Binary Representation
output = sign + exponent_bin + mantissa
print(output)
The output of the above code is ?
01000001000111011110101110000101
Comparison
| Method | Complexity | Best For |
|---|---|---|
| struct module | Low | Simple conversion with standard library |
| NumPy | Low | When already using NumPy in project |
| Manual IEEE 754 | High | Understanding the conversion process |
Conclusion
Use the struct module for simple floating-point to binary conversion. The manual IEEE 754 method helps understand the underlying process, while NumPy provides integration with scientific computing workflows.
