I have a little problem that I can't get my head around.
I add value4 to value2 or value3 depending on if value1 is even or odd. If I can do this without value2 or value3 "rolling over" I do it, otherwise I don't. Atleast that's the function I'm trying to get.
I'm new to both Arduino and any kind of C so I'm sorry if I'm missing something obvious or if the code isn't the most efficient. I'm more used to PLC's
Anyway, here's the code (all variables [value1 - 4] are unsigned integers, 0-65535):
 case case1:
   if (value1 % 2)
    {
     if ((value2 + value4) < 65535){
     value2 = value2 + value4
     }
    }
   else
    {
     if ((value3 + value4) < 65535){
     value3 = value3 + value4;
     }
    }
   break;
I've tried changing the value 65535 to an unsigned int with the same value (65535) without any success.
The funny thing is that when value4 is 1, it doesn't add to value 2 or value3. But when it's anything else it still adds.
I've tried with 10, 100, 1000 and 10000 as a value for value4 without it working.
The code above is within the loop just to make that clear.
case case1:
   if (value1 & 1)  // much faster than %
    {
     if ( 65535 - value2) <= value4)  value2 += value4
    }
   else
    {
     if ((65535 - value3) <= value4)  value3 += value4;
    }
   break;
Rather than hard coding in values for a maximum int (+33.767) or unsigned int (65.535), you could use the following code:
#include <limits.h>
if (UINT_MAX - value2 > value4){
//Â Do your stuff here, there will be no rollover
}
else {
//Â this is where you'd go if the addition would give you a rollover
}
The limits.h header file defines the values you are interested in, but does it in a way that makes your code more portable. Using the symbolic constants like UINT-MAX makes it easier if you move your code from an environment where int's are 2 bytes to one where they are 4 bytes.
Thanks a lot guys. Ofcourse it's true that it will always be less than 65535 because it rolls over.
I'm so used to the PLC-world where a 16-bit variable can't roll over. Sometimes you just need another perspective on things.
Your examples would work fine, but I changed value4 to a long which means it can store more then 65535 and therefore the original code works fine. And yes, I changed the value to an int
Thanks once again!
65535 is a perfectly valid value for unsigned int, its 0xFFFF which fits in 16 bits.
For tests with powers-of-two or values close to a power of two its really helpful
to use hexadecimal since that makes it clear its a power of two and it becomes
obvious if the value is too large to represent, as in:
 if (v < 0x10000)
Where 0x10000 is clearly 17 bits, not 16.
There are also #defined constants for the ends of the integer ranges,