Open In App

How to Convert Binary Data to Float in Python?

We are given binary data and we need to convert these binary data into float using Python and print the result. In this article, we will see how to convert binary data to float in Python.

Example:

Input: b'\x40\x49\x0f\xdb'  <class 'bytes'>
Output: 3.1415927410125732 <class 'float'>
Explanation: Here, we have binary data b'\x40\x49\x0f\xdb' those we converted into float 3.1415927410125732.

Convert Binary Data to Float in Python

Below are some of the methods to convert binary data to float in Python:

Convert Binary data to Float in Python Using struct Module

In this example, below code reads binary data, converts it to a float using the struct module, and prints the resulting float value along with its type.

import struct

# binary data
binary_data = b'\x40\x49\x0f\xdb'
print(type(binary_data))

# Cast binary data to float
float_value = struct.unpack('>f', binary_data)[0]
print("Float value:", float_value)
print(type(float_value))

Output
<class 'bytes'>
Float value: 3.1415927410125732
<class 'float'>

Convert Binary Data to Float Using int.from_bytes() Function

In this example, below code converts binary data into an integer, then unpacks it as a float using struct and convert binary data to float using int.from_bytes() function. It prints the float value and its type.

import struct

binary_data = b'\x40\x49\x0f\xdb'
print(type(binary_data))

int_value = int.from_bytes(binary_data, byteorder='big')
float_value = struct.unpack('>f', int_value.to_bytes(4, byteorder='big'))[0]

print("Float value:", float_value)
print(type(float_value))

Output
<class 'bytes'>
Float value: 3.1415927410125732
<class 'float'>
Article Tags :