Fraction Coding
C2000 Microcontroller Workshop - Numerical Concepts 8 - 11
Fraction Coding
Although COFF tools recognize values in integer, hex, binary, and other forms, they understand
only integer, or non-fractional values. To use fractions within the C28x, it is necessary to describe
them as though they were integers. This turns out to be a very simple trick. Consider the
following number lines:
Coding Traditional 16-bit Q15 Fractions
C-code example: y = 0.707 * x
Fraction
⇒
∗ 32768
(2
15
)
void main(void)
{
int16 coef = 32768*707/1000; // 0.707 in Q15
int16 x, y;
y = (int16)( (int32)coef * (int32)x ) >> 15);
}
~1
½
0
-½
-1
0x7FFF
0x4000
0x0000
0xC000
0x8000
32767
16384
0
-16384
-32768
Integer
By multiplying a fraction by 32K (32768), a normalized fraction is created, which can be passed
through the COFF tools as an integer. Once in the C28x, the normalized fraction looks and
behaves exactly as a fraction. Thus, when using fractional constants in a C28x program, the coder
first multiplies the fraction by 32768, and uses the resulting integer (rounded to the nearest whole
value) to represent the fraction.
The following is a simple, but effective method for getting fractions past the assembler:
1. Express the fraction as a decimal number (drop the decimal point).
2. Multiply by 32768.
3. Divide by the proper multiple of 10 to restore the decimal position.
Examples:
• To represent 0.62: 32768 x 62 / 100
• To represent 0.1405: 32768 x 1405 / 10000
This method produces a valid number accurate to 16 bits. You will not need to do the math
yourself, and changing values in your code becomes rather simple.