Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

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.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top