Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 736
snakile Avatar asked Dec 06 '10 16:12

snakile


People also ask

How do you convert a floating point number to a fixed-point in Matlab?

You can convert floating-point MATLAB® code to fixed-point code using the Fixed-Point Converter app or at the command line using the fiaccel function -float2fixed option. You can choose to propose data types based on simulation range data, derived (also known as static) range data, or both.

How do you convert a decimal to a fixed binary point?

Decimal numbers are converted to binary using division by powers of base 2. The value on the left of the decimal point is divided by 2 to get the remainder as the binary digits right to left from the binary decimal point.

What is fixed-point representation in C?

Fixed-Point Representation −This representation has fixed number of bits for integer part and for fractional part. For example, if given fixed-point representation is IIII. FFFF, then you can store minimum value is 0000.0001 and maximum value is 9999.9999.

How do you add a fixed-point number?

The addition of fixed-point numbers requires that the binary points of the addends be aligned. The addition is then performed using binary arithmetic so that no number other than 0 or 1 is used. The default global fimath has a value of 1 (true) for the CastBeforeSum property.


1 Answers

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.

like image 139
snakile Avatar answered Sep 16 '22 18:09

snakile