Convert hex string to float in Python

In this tutorial, you will learn how to convert a hex string to a float in Python. You cannot directly convert a hex string into a float. First, you have to convert the hex string to bytes, and then the bytes can be converted into a float.

Steps for Conversion:

  • Hex string to Bytes conversion: we use ‘bytes.fromhex(hex_value)‘. Here each pair of hex digits represents one byte.
  • Bytes to Float conversion: we use ‘struct.unpack(‘!f’, byte_value)’. Here ‘!f’ is a specifier that may be a different data type according to the conversation, the ‘struct’  has to be imported from the struct module. ‘unpack()’ is a function in the struct module.
Example to convert hex string to bytes:
>>>bytes.fromhex('12aa01bd')
b'\x12\xaa\x01\xbd'
Example of covert bytes to float:
>>>struct.unpack('!f',b'\x12\xaa\x01\xbd')
(1.0728936830418387e-27,)
Code for the above Example:
import struct #import struct module
string_hex="40490fdb"
convert_byte=bytes.fromhex(string_hex) #conversion of hex string to bytes
float_value=struct.unpack('!f',covert_byte)[0] #coversion of bytes to float value
print(float_value)
output:
3.1415927410125732
Struct module:

This module is used for conversions between Python values and  C structs represented as Python bytes objects. We use

  • struct.pack()
  • struct.unpack()
  • struct.calcsize()
  • struct.pack_into()
  • struct.unpack_from()

Struct pack: This pack is used to pack values into binary data.

Struct unpack: This unpack is used to unpack binary data with specified format codes.

Struct calcsize: This is used to calculate and print the size of the packed binary data for this format.

So in the given code, you can retrieve the hex string from the user using the input() function. So, the struct module is used to convert to float, and also to an integer, long integer, or boolean.

 

Leave a Reply

Your email address will not be published. Required fields are marked *