How to avoid overflows in C code?

Status
Not open for further replies.

future

Newbie level 6
Joined
Dec 20, 2004
Messages
13
Helped
1
Reputation
2
Reaction score
0
Trophy points
1,281
Activity points
109
Avoiding overflows in C

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.
 

Avoiding overflows in C

Hi future,

You can use a longer data type (16 bits signed integers instead of chars). If you need to get 8-bit results (unsigned char), you should check it against the limits (0 and 255) and saturate before convert it to unsigned char.
Regards

Z
 

Re: Avoiding overflows in C

Hi,

I will use the "asm" way..

Code:
   temp=sample0-sample1;                                           //
   if(STATUSbits.N) temp=0;                                        //
   temp=sample0+temp;                                              //
   if(STATUSbits.C) temp=255;                                      //

Thank you.
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…