How about something like this ...smileysam said:I need help in coverting floating point to fixed point
// Set this to the number of desired binary digits to the right of the radix.
#define NUM_FRACT_BIN_DIGITS 8
// The Fixed Point data type, which must be a fundamental type (e.g., int, short, long, etc.).
typedef int FIXEDPOINT;
// Convert float value to fixed point.
FIXEDPOINT FloatToFixed( float val )
{
return (FIXEDPOINT)( val * ( 1 << NUM_FRACT_BIN_DIGITS ) );
}
// Convert fixed point value to float.
float FixedToFloat( FIXEDPOINT val )
{
return (float)val / ( 1 << NUM_FRACT_BIN_DIGITS );
}
// Extract the whole part of a fixed point value.
int IntegerPart( FIXEDPOINT val )
{
return val >> NUM_FRACT_BIN_DIGITS;
}
// Extract the fractional part of a fixed point value.
int FractionalPart( FIXEDPOINT val )
{
return val & ( ( 1 << NUM_FRACT_BIN_DIGITS ) - 1 );
}
FIXEDPOINT a, sum;
float fsum;
a = FloatToFixed( 1.31 ); // a = 335
sum = a + a; // sum = 670
fsum = FloatToFixed( sum ); // fsum = 2.61 (almost 2.62!)
FIXEDPOINT FixedMultiply( FIXEDPOINT a, FIXEDPOINT b )
{
return ( a * b ) >> NUM_FRACT_BIN_DIGITS;
}
FIXEDPOINT a, product;
float fsum;
a = FloatToFixed( 1.31 ); // a = 335
product = FixedMultiply( a, a ); // product = 438
fproduct = FloatToFixed( product ); // fproduct = 1.71