Show Posts
Pages: 1 [2]
16  Using Arduino / Programming Questions / Re: Addition overflow on: November 07, 2012, 01:37:21 pm
You can but doing so is "dangerous".  The compiler can reorder (or even remove) code when it optimizes.  When you write this...

Yes, the compiler optimizer is always surprising.

This guy (http://www.fefe.de/intof.html) says that if an addtion  of integers owerflowed, then the sum is always less than either addend. (I do not know the reason)

Then, say, we have A which is an integer of 48 bits, consisting A_Hi (16 bits) and A_Low (32 bits) and we add B which is a 32-bit integer.

Maybe something like that would work

Code:
unsigned int A_Hi;
unsigned long A_Low;
unsigned long B;

A_Low += B;
if(B > A_Low) A_Hi ++;

(I apologize for my horrid English)
17  Using Arduino / Programming Questions / Re: Addition overflow on: November 07, 2012, 08:24:36 am
I think, but am not sure, you can access the microcontroller "status register" from C code.

I think in "Arduino C" there is a special variable called "SREG" which is a representation of the status register of the microcontroller. The microcontroller status register contains a collection of flags and one of those flags is the carry flag. I think the carry flag is the flag in the status register bit0 .

You could try something like this:

Code:
boolean isCarryOverflow()
{
return(SREG & 0x01); //Assuming the carry flag in on bit0
}

void setup()
{
...
...
c = a + b;
if(isCarryOverflow)
{
...
}
...
}

ATmega datasheet >> http://www.atmel.com/Images/doc8161.pdf (page 10)
http://www.wvshare.com/article/AVR-1-1-5.htm

You can download the datasheet of your Arduino microcontroller from arduino.cc >> Products
Pages: 1 [2]