4 thoughts on “Representing floats as a series of hex values”
Does anyone have any ideas on how to represent a float value as 4 hexadecimal values when the struct module is unavailable? In C you would just cast a float* to an uint8_t* and iterate over the 4 bytes but I cannot figure out how to concatenate them back to a float in Python.
An example please?
3.14 is represented as 0x4048f5c3 or [0x40 0x48, 0xf5, 0xc3] when using IEEE754 floating point notation. This can easily be sent as 4 bytes from a C program and then decoded back to a float using the python struct module:
>>> struct.unpack('>f', 'x40x48xf5xc3')
(3.140000104904175,)
However, since the Telit interpreter lacks this module it becomes trickier. Anyway, I rolled my own decoder which turned out to be fairly trivial. A bit slow, perhaps:
def get_float(data):
"""
Extracts a float value encoded as IEEE 754 single point precision.
@param data: List to read data from.
@return: Data converted to a single precision floating point value.
We use cookies to enhance your browsing experience and help us improve our websites. To improve our website, we carefully select third parties that use cookies to allow us to serve specific content and achieve the purposes set out in our cookie policy. For more information on how to make adjustments through your browser to the cookies being used on your device, please click Find Out More link. By closing this banner or continuing to browse our website, you agree to our use of such cookies. FIND OUT MORE
Does anyone have any ideas on how to represent a float value as 4 hexadecimal values when the struct module is unavailable? In C you would just cast a float* to an uint8_t* and iterate over the 4 bytes but I cannot figure out how to concatenate them back to a float in Python.
An example please?
3.14 is represented as 0x4048f5c3 or [0x40 0x48, 0xf5, 0xc3] when using IEEE754 floating point notation. This can easily be sent as 4 bytes from a C program and then decoded back to a float using the python struct module:
>>> struct.unpack('>f', 'x40x48xf5xc3')
(3.140000104904175,)
However, since the Telit interpreter lacks this module it becomes trickier. Anyway, I rolled my own decoder which turned out to be fairly trivial. A bit slow, perhaps:
def get_float(data):
"""
Extracts a float value encoded as IEEE 754 single point precision.
@param data: List to read data from.
@return: Data converted to a single precision floating point value.
"""
int_val = get_uint32(data)
SIGN_MASK = 0x80000000
EXP_MASK = 0x7F800000
FRAC_MASK = 0x7FFFFF
# Extract sign, the most significant bit
negative = int_val & SIGN_MASK
# Extract exponent
exp = ((int_val & EXP_MASK) >> 23) - 127
# Calculate significand
sig = 0x800000 | (int_val & FRAC_MASK)
sig = float(sig) / 0x800000
# Calculate final float value.
val = sig * (2 ** exp)
return -val if negative else val
Much appreciated Marco!