I need to know if there is a way to "avoid multiplication overflow"
I explain :
actually I have :
Code:
int a=2,b=200,c;
c = a*b;
by this code, I obtain c = 144 , cf 0 <= c <= 255
but I would like to avoid overflow and obtain c = 255
How can I do that?
thanks for your help
Spilz
RF_Developer
Joined: 07 Feb 2011 Posts: 839
Posted: Fri Sep 07, 2012 3:31 am
There is no way to "avoid" the overflow; overflow behaviour is fixed in the harware; what you are wanting to do is deal with the overflow in a different way.
So you have to do it in 16 bit arithmetic and then limit/clamp the result to 8 bits:
Code:
// Don't forget ints in CCS C are 8 bit unsigned. The same method
// works for other sizes & signedness with suitable modifications.
int a=2,b=200,c;
int16 Temporary;
Temporary = (int16) a * b; // Only need to cast one of the operands. Casting both makes no difference; just takes longer to type!
if (Temporary > 255)
{
c = 255;
}
else
{
c = Temporary; // Note this invloves an implied truncation of the result.
}
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum