0

when using left shift and Big-integer i get different results to when i use hard coded number, why is that and how can it be overcome?

    BigInteger num = 1779033703;
    BigInteger result = num << 30;
    Console.WriteLine(result);
    Console.WriteLine(1779033703 << 30);

Result

1910222893216694272

-1073741824

  • Because the "hard coded value" is an `int` and they can only hold 32 bits to represent a number. `BigInteger` exists specifically to allow you to work with larger integer values. – juharr Dec 31 '17 at 21:39
  • Possible duplicate of [No overflow exception for int in C#?](https://stackoverflow.com/questions/2056445/no-overflow-exception-for-int-in-c) – Progman Dec 31 '17 at 22:02

1 Answers1

2

Because with 1779033703 << 30 on a regular int (a 32-bit signed integer), you are hitting the overflow, hence it starts from int.MinValue again. The BigInteger can handle much larger values, and is thus not affected by overflow.

Try to use a long (a 64-bit signed integer), and you will see you get the same result as with the BigInteger.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325