Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does int.MinValue % -1 cause and OverflowException [duplicate]

In 7.8.3. of the C# Specification regarding the Remainder operator it states the following:

If the left operand is the smallest int or long value and the right operand is -1, a System.OverflowException is thrown.

Therefore int.MinValue % -1 would result in an OverflowException. I am trying to understand why?

like image 565
Dirk Strauss Avatar asked Nov 25 '15 23:11

Dirk Strauss


1 Answers

In two's complement arithmetic, data types have a range from (-2**n) to (2**n - 1) (where 'n' is 1 less than the number of bits in the data type).

For example, a 16-bit signed integer has a valid range from -32768 (-2**15) to 32767 (2**15 - 1).

-32768 / -1 = +32768 which exceeds the valid range for a 16-bit signed integer.

like image 52
keithmo Avatar answered Oct 07 '22 18:10

keithmo