How do I convert a floating point C code to fixed point?

snakile picture snakile · Dec 6, 2010 · Viewed 20.9k times · Source

I have a C code which uses doubles. I want to be able to run the code on a DSP (TMS320). But the DSP doesn't support doubles, only fixed-point numbers. What is the best way to convert the code into fixed-point? Is there a good C library for fixed-point numbers (implemented as integers)?

Answer

snakile picture snakile · Mar 21, 2011

The following code defines a type Fixed, using integers as its internal representation. Additions and subtractions are performed simply with the + and - operators. Multiplication is performed using the defined MULT macro.

#include <stdio.h>
typedef int Fixed;

#define FRACT_BITS 16
#define FRACT_BITS_D2 8
#define FIXED_ONE (1 << FRACT_BITS)
#define INT2FIXED(x) ((x) << FRACT_BITS)
#define FLOAT2FIXED(x) ((int)((x) * (1 << FRACT_BITS))) 
#define FIXED2INT(x) ((x) >> FRACT_BITS)
#define FIXED2DOUBLE(x) (((double)(x)) / (1 << FRACT_BITS))
#define MULT(x, y) ( ((x) >> FRACT_BITS_D2) * ((y)>> FRACT_BITS_D2) )

I was using the above code to represent fractions in my image processing algorithm. It was faster than the version which was using doubles and the results were almost exactly the same.