The Wayback Machine - https://web.archive.org/web/20240801130518/https://www.geeksforgeeks.org/convert-hex-string-to-float-in-python/
Open In App

Convert hex string to float in Python

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Converting a hex string to a float in Python involves a few steps since Python does not have a direct method to convert a hexadecimal string representing a float directly to a float. Typically, a hexadecimal string is first converted to its binary representation, and then this binary representation is interpreted as a floating-point number.

Convert hex string to float in Python

There are different ways in Python to convert a hex string to a floating point.

Here is a step-by-step guide on how to achieve this:

Using the module struct

Python has a struct module that provides functions that can convert between values in Python and C structs represented as Python bytes objects. It is beneficial when working with binary data from network connections or files.

Example:

Start by deleting any leading or trailing spaces and removing the ‘0x’ prefix if it is present in the hex string. After this, turns the hex string into a byte array using bytes.fromhex(). Lastly, by looking at the byte array as float with format If then returning floating-point number which will make use of struct.unpack().

Python
import struct

def hex_to_float_struct(hex_str):
    hex_str = hex_str.strip().replace("0x", "")
    byte_array = bytes.fromhex(hex_str)
    float_num = struct.unpack('!f', byte_array)[0]
    return float_num

# Example
hex_str = "40490fdb"
print(hex_to_float_struct(hex_str))  

Output:

3.1415927410125732

Using binascii

Another module within the python library is binascii and it offers various methods for representing binary data of ASCII encoded strings. The procedure includes converting hexadecimal representation of a string to binary then interpreting this binary as a float.

Example:

By running these hex strings through binascii.unhexlify() function first into a byte array and finally calling struct.unpack() with format !f before returning them back together with other numbers.

Python
import binascii
import struct

def hex_to_float_binascii(hex_str):
    byte_array = binascii.unhexlify(hex_str)
    float_num = struct.unpack('!f', byte_array)[0]
    return float_num

# Example
hex_str = "40490fdb"
print(hex_to_float_binascii(hex_str))  

Output

3.1415927410125732

Using Raw Byte Manipulation

The method begins by converting the hex string to bytes and then to floating-point without any high level modules like struct.

Example:

This code converts the hexadecimal string into an integer of 16 bases it does this by using the int() function. It also changes the number to byte array with top-down approach consisting of four bytes. Finally, struct.unpack() which uses format !f is used in order to unpack byte array for creation of floating point number.

Python
import struct

def hex_to_float_manual(hex_str):
    int_value = int(hex_str, 16)
    byte_array = int_value.to_bytes(4, byteorder='big')
    float_num = struct.unpack('!f', byte_array)[0]
    return float_num

# Example 
hex_str = "40490fdb"
print(hex_to_float_manual(hex_str))  

Output:

3.1415927410125732

Conclusion

Each method has its own benefits depending on what they are trying to achieve in a given context. Going through these steps will help you effectively convert Hex string to Float when programming with Python.


Similar Reads

Convert Hex To String Without 0X in Python
Hexadecimal representation is a common format for expressing binary data in a human-readable form. In Python, converting hexadecimal values to strings is a frequent task, and developers often seek efficient and clean approaches. In this article, we'll explore three different methods to convert hex to string without the '0x' prefix in Python. Conver
2 min read
Convert Hex String To Integer in Python
Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this task. In this article, we will explore various method
2 min read
Convert Hex to String in Python
Hexadecimal representation is a common format for expressing binary data in a human-readable form. Converting hexadecimal values to strings is a frequent task in Python, and developers often seek efficient and clean approaches. In this article, we'll explore different methods to convert hex to string in Python. Convert Hex To String In PythonBelow,
2 min read
Convert Hex String to Bytes in Python
Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. In Python, converting a hex string to bytes is a frequent task, and there are various methods to achieve this. In this article, we will explore some simple and commonly used methods for converting a hex string to b
3 min read
Convert Python String to Float datatype
Let us see how to convert a string object into a float object. We can do this by using these functions : float() decimal() Method 1: Using float() # declaring a string str1 = "9.02" print("The initial string : " + str1) print(type(str1)) # converting into float str2 = float(str1) print("\nThe conversion of string to float i
2 min read
Convert String to Float in Python
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting the string to float. In Python, we can use float() to convert String to float. and we can use int() to convert a String to an integer. Input: "33.28" Output: 33.28 # float Explanation: int in input a
3 min read
Convert String with Comma To Float in Python
When working with data in Python, it's not uncommon to encounter numeric values formatted with a mix of commas and dots as separators. Converting such strings to float is a common task, and Python offers several simple methods to achieve this. In this article, we will explore five generally used methods for converting a string with a comma separato
3 min read
Cannot Convert String To Float in Python
Python, a versatile and powerful programming language, is widely used for data manipulation and analysis. However, developers often encounter challenges, one of which is the "Cannot Convert String To Float" error. This error occurs when attempting to convert a string to a float, but the string's content is incompatible with the float data type. In
3 min read
Python Hex String to Integer List
Hexadecimal strings are commonly encountered when working with low-level programming, networking, or cryptographic applications. In Python, converting a hex string to an integer array or list is a frequent task. In this article, we'll explore some different methods to achieve this conversion. Hex String To Integer Array We change a Hex string into
3 min read
How to Convert String to Float in Pandas DataFrame
Converting Strings to Float in Pandas DataFrame is a very crucial step for data analysis. Converting string to float values can help you perform various arithmetic operations and plot graphs. In this article, we'll look at different ways to convert a string to a float in DataFrame. Creating Sample Dataframe Now, let's create a DataFrame with 'Year'
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg