Mark As Completed Discussion

Integer Underflow

Normally, integer underflow refers to storing a value which is too small and falls outside the range allowed by the space reserved for that variable. An example is shown below:

1var x = -128;
2console.log("Original: " + x);
3x--;
4if (x < -128) x += 256; // Simulate byte underflow
5console.log("After decrement: " + x);

The output of the code is shown below:

TEXT
1Original: -128
2After decrement: 127

This is also wraparound, but in the opposite direction. Now the value has wrapped around towards a large positive value when trying to store a smaller value (-129) outside the range of the byte type variable (-128 to 127). To see why we have a +127, you can apply rules for integer subtraction. To do x-y, we take the two's complement of y and add it to x. Hence:

TEXT
1Binary representation of x: 0b10000000
2Two's complement of 1 is: 0b11111111
3Add x and two's complement of 1: 0b101111111
4Actual Result stored by taking the 8 least significant bits: 0b01111111 
Integer Underflow