Wonder why. C# .Net 3.5
int a = 256 * 1024 * 1024;
int b = 8;
long c = b * a;
Console.WriteLine(c);//<-- result is -2147483648
Where do
The maximum value that int
supports is 2147483647
. The expected result 2147483648
does not fit in this type range, hence an overflow occurs causing the result to be negative.
Note that the statement long c = b * a;
translates to the following two steps:
Multiple the int
values of b
and a
. The int
result is negative due to integer overflow.
Convert the already negative result to long
.
Try casting to long
before multiplying:
long c = b * (long) a;
or declare a
be of type long
:
long a = 256L * 1024L * 1024L;