This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

convert c_float to ieee_11073_16bit_float

Hello,

I need to convert a standard 32 bit floating point number to IEEE-11073 16-bit FLOAT with 12-bit mantissa and 4-bit exponent (source: https://infocenter.nordicsemi.com). Is there already an implementation in the sdk or an example somewhere? I tried it the following way, but the numbers in the nrf connect app where wrong.


#include "ble_bps.h"
ieee_float16_t c_float32_to_ieee_11073_float16(float input)
{
    ieee_float16_t ret;
    uint32_t input_raw = *((uint32_t*)&input);
    ret.mantissa = (input_raw >> 23) & 0xf;
    ret.exponent = (input_raw & 0xfff);
    return ret;
}

Parents Reply Children
  • Your right, thanks. I added an -INF and +INF limitation. For convinience, I set the max values a little bit less than the real limits of the 16 bit float. This should solve the issue.

     

    ieee_float16_t c_float32_to_ieee_11073_float16(float input)
    {
    	ieee_float16_t ret;	
    	if(input != input) //check for NAN
    	{
    		ret.exponent = 0;
    		ret.mantissa = 0x07ff;
    		return ret;
    	}
    	else if(input > (float)2E10) //check for +INF
    	{
    		ret.exponent = 0;
    		ret.mantissa = 0x07FE;
    		return ret;
    	}
    	else if(input < (float)-2E10) //check for -INF
    	{
    		ret.exponent = 0;
    		ret.mantissa = 0x0802;
    		return ret;
    	}
    	else
    	{
    		ret.exponent = 0;
    		while(input > (float)0x7ff){
    			input /= 10;
    			ret.exponent += 1;
    		}
    		while(input*10 < (float)0x7ff){
    			input *= 10;
    			ret.exponent -= 1;
    		}
    		ret.mantissa = ((int16_t)input) & 0xfff;
    		ret.exponent &= 0xf;
    		return ret;
    	}
    }

  • Given that the largest mantissa is 2^11 - 1, and the largest exponent is 7,
    the largest number you can represent will be (2^11 - 1) * 10^7 = 2.047 * 10^10

    The precision of the mantissa will cause significant errors with very large or very small values, ie
    the number 123456789: exp = 5, mantissa = 1235 --> 0.1235 * 10^5 = 123500000.

    or 0.000001234567: exp = -5, mantissa = 1235 --> 0.1235 * 10^-5 =  0.000001235.

    This is from my limited understanding, it might be wrong. 

    There are also at least 5 cases that need to be handled differently:

    1. input == zero.
    2. input >= 1.0
    3. input < 1.0
    4. input >= -1.0
    5. input < -1.0
Related