Bra*_*ann 7 .net math 64-bit integer-overflow int64
我在.net程序中见证了一个奇怪的行为:
Console.WriteLine(Int64.MaxValue.ToString());
// displays 9223372036854775807, which is 2^63-1, as expected
Int64 a = 256*256*256*127; // ok
Int64 a = 256*256*256*128; // compile time error :
//"The operation overflows at compile time in checked mode"
// If i do this at runtime, I get some negative values, so the overflow indeed happens.
Run Code Online (Sandbox Code Playgroud)
为什么我的Int64的行为就像它们是Int32的一样,虽然Int64.MaxValue似乎证实它们使用的是64位?
如果它是相关的,我使用32位操作系统,目标平台设置为"任何CPU"
Jon*_*eet 20
您的RHS仅使用Int32
值,因此使用Int32
算术执行整个操作,然后将Int32
结果提升为long.
把它改成这个:
Int64 a = 256*256*256*128L;
Run Code Online (Sandbox Code Playgroud)
一切都会好的.