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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With