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

Avoiding overflows in C

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



Joined: 14 May 2004
Posts: 330

View user's profile Send private message

Avoiding overflows in C
PostPosted: Tue Dec 21, 2004 10:48 am     Reply with quote

Hello,

Analysing this code:

Code:
          tperiod2=tperiod1;                                              //
          tperiod1=tperiod0;                                              //
          tperiod0=wperiod0;                                              //

          predict_tmr=(tperiod0+(tperiod0-tperiod1)) +                    //
                      (tperiod0-tperiod1-(tperiod1-tperiod2));            //


All being chars ranging from 30 to 255, based in the rate of change of the last, it can predict the new sample.. but when it is growing and close to 255 it overflows, also when diminishing close to 0.

I am looking for a way to avoid overflows in this case and others.

Thank you.
SherpaDoug



Joined: 07 Sep 2003
Posts: 1640
Location: Cape Cod Mass USA

View user's profile Send private message

Re: Avoiding overflows in C
PostPosted: Tue Dec 21, 2004 11:55 am     Reply with quote

Can you offset them to longs?
Code:
         
          predict_tmr=(int)((tperiod0+(10000+tperiod0-tperiod1)) +                    //
                      (tperiod0-tperiod1-(10000+tperiod1-tperiod2)))-20000;            //

The two 10000's should force the math to be done with longs, and avoid any posibility of going negative. Just take 20000 off the end and cast back to int.
_________________
The search for better is endless. Instead simply find very good and get the job done.
future



Joined: 14 May 2004
Posts: 330

View user's profile Send private message

PostPosted: Tue Dec 21, 2004 3:30 pm     Reply with quote

Well, I did the ASM way

Code:
   temp=sample0-sample1;                                           //
   if(STATUSbits.N) temp=0;                                        //
   temp=sample0+temp;                                              //
   if(STATUSbits.C) temp=255;                                      //
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