Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a float into hex

Tags:

In Python I need to convert a bunch of floats into hexadecimal. It needs to be zero padded (for instance, 0x00000010 instead of 0x10). Just like http://gregstoll.dyndns.org/~gregstoll/floattohex/ does. (sadly i can't use external libs on my platform so i can't use the one provided on that website)

What is the most efficient way of doing this?

like image 658
user2339945 Avatar asked May 13 '14 06:05

user2339945


People also ask

How do you convert a floating number to hexadecimal?

Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.

How do you convert to hexadecimal?

To convert a hexadecimal to a decimal manually, you must start by multiplying the hex number by 16. Then, you raise it to a power of 0 and increase that power by 1 each time according to the hexadecimal number equivalent. We start from the right of the hexadecimal number and go to the left when applying the powers.

How do you convert hex to float in Python?

int i = 0x41973333; float f = *((float*)&i); and that's exactly what the Python code using the ctypes library is doing in my example. I used your method to convert a hex string to float and it returns a wrong value.


1 Answers

This is a bit tricky in python, because aren't looking to convert the floating-point value to a (hex) integer. Instead, you're trying to interpret the IEEE 754 binary representation of the floating-point value as hex.

We'll use the pack and unpack functions from the built-in struct library.

A float is 32-bits. We'll first pack it into a binary1 string, and then unpack it as an int.

def float_to_hex(f):     return hex(struct.unpack('<I', struct.pack('<f', f))[0])  float_to_hex(17.5)    # Output: '0x418c0000' 

We can do the same for double, knowing that it is 64 bits:

def double_to_hex(f):     return hex(struct.unpack('<Q', struct.pack('<d', f))[0])  double_to_hex(17.5)   # Output: '0x4031800000000000L' 

1 - Meaning a string of raw bytes; not a string of ones and zeroes.

like image 191
Jonathon Reinhart Avatar answered Sep 20 '22 13:09

Jonathon Reinhart