curious_mind
Full Member level 4
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?
Follow along with the video below to see how to install our site as a web app on your home screen.
Note: This feature may not be available in some browsers.
how to take care of oveflow for addition and subtraction? c should be short or long?
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);
}
Not when represented with long data type as in post #12.so 65535 is around -1