Fiddling with Arduinos, about integer overflows

Posted on Feb 27, 2014 | Categories: coding, arduino


Today an Arduino ethernet board was delivered for me. As excited as I was I unpacked it, attached it to my pc, and just started programming it. First thing I usually do is to print some stuff over the serial connection just to see it working.

#include
int i;

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.println(i);
  i++;
}

This was it all. I saw some numbers being printed so it was working. I continued programming but when I looked at the terminal again I saw negative numbers. It made me wonder again why the numbers turn negative.

Integer Overflow

In the picture above you see three things:

The count reaching 32767 The count turning to -32768 The count countin up from -32768 Starting at the end, the count counts up from -32768, well, this is as it should be. (Remember the i++ in tha code) But, why falls the count from 32767 to -32768? To reach the 32768 count you have to use an additional bit in the array. To understand what exactly is happening on bit level we’ll compare some bit storage systems. In this article I’m talking about signed integers. Here I show the value of 32767:

0111111111111111

And translating the binary to decimals:

Binary locations:
  0     0    0    0    0    0    0   0   0  0  0  0  0 0 0 0
Decimal values:
32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1

Our binary:
  0     1    1    1    1    1    1   1   1  1  1  1  1 1 1 1

As you probably see there’s an additional byte needed to reach the count of 32768.

Well, to know how the computer stores signed integers I’ll write about two different methods on storing signed ints. The first one is the “Ones’ Complement” and the second one is the “Two’s Complement”.

Ones’ Complement

This system uses a prefix on the bit array. Is the last bit a zero, then the value is positive. Negative values are a little bit more difficult. With negative values the last bit is a one, but, there’s another counting system used. 1000 hasn’t the decimal value of 8 but it has the decimal value of -7.

Another example, which is probably easier to understand: 1110 hasn’t the decimal value of 14 but has the decimal value of -1. So, if the last bit in this system is a 1, then you have to count the 0 as 1 and the 1 as 0.

Pretty easy system. To convert 1234 to -1234 you only have to swap 1 with 0 and 0 with 1.

Two’s Complement

The counting in this system is almost the same, however, you have to subtract one additional number. this means that 1111 has the value of -1 and that 1110 has the decimal value of -2. Maybe this comparison table found on Wikipedia says more than I could type here: http://en.wikipedia.org/wiki/Signed_number_representations#Comparison_table