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?
In Python
float
is always double-precision.If you require your answer to be output in the form of a hexadecimal integer, the question was already answered:
However you might instead consider using the builtin function:
This is the same answer as before, just in a more structured and human-readable format.
The lower 52 bits are the mantissa. The upper 12 bits consists of a sign bit and an 11-bit exponent; the exponent bias is 1023 == 0x3FF, so 0x403 means '4'. See Wikipedia article on IEEE floating point.
if you are on micropython (which is not said in the question, but I had trouble finding) you can use this
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
andunpack
functions from the built-instruct
library.A
float
is 32-bits. We'll firstpack
it into a binary1 string, and thenunpack
it as anint
.We can do the same for
double
, knowing that it is 64 bits:1 - Meaning a string of raw bytes; not a string of ones and zeroes.
Further to Jonathon Reinhart's very helpful answer. I needed this to send a floating point number as bytes over UDP