Description
While trying to troubleshoot a problem I was having with INT roll over I ran across the following erratic behavior that I can not explain. Can anyone shed sone light on what's happening here?
I tried the following code on the Arduino Mega 2560:
void setup() {
int x = 32766;
Serial.begin(19200);
for (int a = 0; a < 5; a++) {
Serial.print(x);
Serial.print("\t");
Serial.println(x, BIN);
x += 1;
}
}
void loop() {
}
and received the following output:
32766 111111111111110
32767 111111111111111
32767 111111111111111
32767 111111111111111
32767 111111111111111
I was expecting the following:
32766 111111111111110
32767 111111111111111
-32768 1000000000000000
-32767 1000000000000001
-32766 1000000000000010
When I changed the initial value of x from 32766 to 32765 (one less) I got the following output:
32765 111111111111101
32766 111111111111110
32767 111111111111111
-32768 11111111111111111000000000000000
-32767 11111111111111111000000000000001
The decimal representation was now correct however, the binary representation has 16 additional significant bits.
Can anyone explain why I'm getting these results?