Thursday, April 6, 2017

float to int...Interesting difference between TYPECASTING and Ceiling/Flooring/Truncating/Rounding

int a;
float b = 3.45f;
b = b * 3.142f;  /* which is 10.8399
a = (int)b;
printf("%f, %d", b,  a);

here b = 10.8399 and a = 10

this above mentioned method is where, typecasting is used for float to int conversion.
This is not the right way always.
Because it depends on the standards that are used when writing the compiler. How compiler will replace this conversion process.
Usually in C99, it uses truncation when converting float to int. But its not usually desirable, as you can see in the above example use expect it would be 11 rather than 10.

So, in these scenarios one should always use float to int conversion method as per the requirement of the application. There are functions readily available in math.h

  1. ceiling: eg. 10.78-> 11; 10.44 -> 11; 7.5->8; -11.89 -> -11; -11.14->-11; -7.5 -> -7
  2. flooring: eg. 10.78-> 10; 10.44 -> 10; 7.5->7; -11.89 -> -12; -11.14->-12;  -7.5 -> -8
  3. truncating: eg. 10.78-> 10; 10.44 -> 10; 7.5->7; -11.89 -> -11; -11.14->-11; -7.5 -> -7
  4. rounding: eg. 10.78-> 11; 10.44 -> 10; 7.5 -> 8; 8.5->9; -11.89 -> -12; -11.14->-11; -7.5 ->-8; -8.5->-9
  5. rounding even:  eg. 10.78-> 11; 10.44 -> 10; 7.5 -> 8; 8.5->8; -11.89 -> -12; -11.14->-11; -7.5 -> -8; -8.5->-8
I think this is a very important point when your application is demanding precision. Hope it helps

Tuesday, April 4, 2017

Effect of variable typecasting, on the underneath assembly code size


  1. Whenever we type-cast we are actually adding or no-effect on the number of instructions added to code.
  2. If lets say, the controller is 16-bit, and we have uint32_t a = 5, b; b = a *10;
  3. In this case b = a*10 will be performed in 2 parts multiplication. Hence a single multiplication will be replaced by two multiplications
  4. If we typecast it like, b = (uint16_t)a * 10; then it will be replaced by code which will be a single cycle multiplication operation.
  5. Int to float or vice-verse takes lot of time, as the numbers are representations are different and there will instructions of number conversion getting added. This will increase the processing time a lot, even though you see it as a simple one line multiplication in C code.
  6. Hence, always be careful when declaring float in the code. If you dont need that kind of precision, dont use it. Use Fixed point representation instead.
  7. Probably down casting a variable usually reduces the underneath instructions
  8. Processor lets say of 32bit will be optimally used if the data variables to be processed are of size 32bit

PROFILE

My photo
India
Design Engineer ( IFM Engineering Private Limited )

Followers