Tag Archives: int.maxvalue to int.minvalue

Some fun with binary math

In this  blogpost, let's play around a bit with math in C#.

Now let's just go over the normal math | x + 1 = x + 1 |.

In most cases of programming, this will be so, but what if x + 1 = -x - 1?

Well this is what is going to happen in the following example.

With some magic(?) we'll make | 2147483647 + 1 = -2147483648 |

Here we have assigned a variable x to int.MaxValue,
now if you press CTRL + D + I you'll open the immediate window in which you can
view the value produced here

 

But let's look at this in a way I like a bit more,
rightclick on MaxValue and you'll see this:

If you go to the definition you get a better view of  this.

So in this piece of code, what var y actually stands
for is "var y = 2147483647 + 1".

Executing this code gets us to this window

 

int.MaxValue + 1 = int.MinValue

Why is this? to give an explenation to this, we have
to look at the binary side of this story.

2147483647 in binary = 1111111111111111111111111111111

Now if you do this (in 32 bit) + 1 you get

 

01111111111111111111111111111111

+          00000000000000000000000000000001

=          10000000000000000000000000000000

 

(1 + 1 = 0 with 1 being carried over)

Now in binary math, the first bit indicated the sign
of the number. (1 being negative and 0 being positive)

With +1 we went from the most positive possible int32
value to the most negative one.

You can probably see that this isn't very good,
because it makes no sense in normal math, so to avoid bugs we'll want an error
to be thrown at runtime.

 

To achieve this, we have to add a Checked { .. } tag  to the code

Here exactly the same calculation happens as before,
but this time the result won't be -214783648 but instead it the program will crash.

"This calculation has resulted in an overflow." is the error that gets thrown here.

The compiler doesn't catch this error while you're
writing your code, it's during runtime that the exception get's thrown.