this one works but yr has to be a long. if int you get wrong answers.
char buf[11];
int dy = 16;
int mo = 6;
long yr = 21;
long xx = 0;
xx = dy;
xx += mo * 100;
xx += yr * 10000;
ltoa(xx, buf, 10);
Serial.println("date "); Serial.println(buf);
but this one gives wrong answers even tho 21 easily fits into int.
char buf[11];
int dy = 16;
int mo = 6;
int yr = 21;
long xx = 0;
xx = dy;
xx += mo * 100;
xx += yr * 10000;
ltoa(xx, buf, 10);
Serial.println("date "); Serial.println(buf);
void setup()
{
Serial.begin(115200);
char buf[11];
int dy = 16;
int mo = 6;
int yr = 21;
long xx = 0;
xx = dy;
xx += mo * 100L; // add L to force long calculation
xx += yr * 10000L; // add L
ltoa(xx, buf, 10);
Serial.println("date "); Serial.println(buf);
}
void loop()
{
}
The L in the calculations force the calculation to be done with long data type. See here.
I had surmised the compiler would use the target for the answer as the workplace or define a long to multiply the two ints. But I guessed wrongly I guess.
C doesn't care: "You want overflow? I got your stinkin' overflow right here!"
The compiler looks at the expression first and decides it's all ints, so ok, integer math. Oh look, he wants to put it in a long comes later, after the overflow.