0

We have an instance where a value being assigned to an integer is larger than the int max value (2,147,483,647). It doesn't throw an error, it just assigns a smaller number to the integer. How is this number calculated?

This has been fixed by changing the int to a long but I'm interested as to how the smaller value is being calculated and assigned to the int.

2 Answers2

3

int contains a 32-bit number which means, it has 32 binary digits of 0 or 1 (first digit means plus for 0 and minus for 1), for example:

1 in decimal  == 0000 0000 0000 0000 0000 0000 0000 0001 as int32 binary
2 147 483 647 == 0111 1111 1111 1111 1111 1111 1111 1111

So, if you'll increment int.MaxValue, you will get next result:

2 147 483 648 == 1000 0000 0000 0000 0000 0000 0000 0000

In two's complement representation this binary number equals to int.MinValue or -2 147 483 648

Taras Shevchuk
  • 326
  • 3
  • 14
0
int.MaxValue:    2,147,483,647

The logic in loops is keeping track of the lowest number found. You can use int.MaxValue to start the value really high, and then any lower number will be valid.

Sample code:

using System;

class Program
{
static void Main()
{
int[] integerArray = new int[]
{
    10000,
    600,
    1,
    5,
    7,
    3,
    1492
};

// This will track the lowest number found
int lowestFound = int.MaxValue;

foreach (int i in integerArray)
{
    // By using int.MaxValue as the initial value,
    // this check will usually succeed.
    if (lowestFound > i)
    {
    lowestFound = i;
    Console.WriteLine(lowestFound);
    }
}
}
}

Output

10000
600
1
Thennarasan
  • 698
  • 6
  • 11