# fixed point arithmetic in c

1. ## fixed point arithmetic in c

I am looking for a C code to perform Q15 addition, subtraction, multiplication, division , sine(x) and cosine(x). Can anybody provide good reference that works?  Reply With Quote

2. ## Re: fixed point arithmetic in c

I'd start with searching "fixed point [add/subtract/mult]" etc. There are different options for each. Saying its fixed point also doesn't tell us if you have hardware multiply/divide support though I'll assume no.

Understand that a lot of it comes down to designing your algorithms around the limitations. For example if you don't have hardware multiply then plan around doing power of 2 shift divides with << and >>. Sin and cos are typically implemented with a look-up-table.  Reply With Quote

•

3. ## Re: fixed point arithmetic in c

short a, b, c;
Addition: c = a + b;
Subtraction: c = a - b;
Multiplication: c = (short)((a * (long)b) >> 15);  Reply With Quote

•

4. ## Re: fixed point arithmetic in c

how to take care of oveflow for addition and subtraction? c should be short or long?  Reply With Quote

•

5. ## Re: fixed point arithmetic in c Originally Posted by curious_mind how to take care of oveflow for addition and subtraction? c should be short or long?
You'd need to use long - or an MCU that supports saturating fixed-point types.  Reply With Quote

6. ## Re: fixed point arithmetic in c

Hi

I am considering 2's complement unsigned data that varies from 0 to 65535. What would happen if I would add 10 with 32767. The result is a negative number. How would I guard this?  Reply With Quote

7. ## Re: fixed point arithmetic in c

Your specification is rather shallow. You say "take care of overflow". How? Saturate? Generate an exception?

In case, additional code is required. The CPU may be already able to detect a signed integer overflow. Or you detect it by monitoring the arguments and result signs.  Reply With Quote

8. ## Re: fixed point arithmetic in c

I came up with the following custom c code. Your view on this will be helpful
Code:
```unsigned int add (unsigned int a ,unsigned  int b)
{
unsigned int res;
unsigned long tmp;
tmp=a+b;
if((a<=32767) && (b<=32767))   // both numbers are positive
{
if (tmp>32767)
{
res=32767;
}
}

else if((a>32767) && (b>32767))  // both numbers are negative
{
if (tmp>32768)
{
res=32768;
}
}
else
{
res=tmp & 0xffff;
}
return(res);
}

unsigned int sub (unsigned int a ,unsigned  int b)
{
unsigned int res;
unsigned long tmp;

if((a<=32767) && ( b>=32768) || (a>=32768) && (b<=32767))
{
if(a>b)
{
res=32768;
}
else
{
res=32767;
}
}
else
{
tmp=a-b;
res=tmp & 0xffff;
}

return(res);
}```  Reply With Quote

•

9. ## Re: fixed point arithmetic in c

Looks O.K. as a demonstration but can be coded more efficiently using bit operations.  Reply With Quote

--[[ ]]--