CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

how to avoid multiplication overflow ?

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
spilz



Joined: 30 Jan 2012
Posts: 219

View user's profile Send private message

how to avoid multiplication overflow ?
PostPosted: Fri Sep 07, 2012 3:07 am     Reply with quote

hello everybody

I need to know if there is a way to "avoid multiplication overflow"
I explain Smile :

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

View user's profile Send private message

PostPosted: Fri Sep 07, 2012 3:31 am     Reply with quote

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.
}


RF Developer
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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


Powered by phpBB © 2001, 2005 phpBB Group