Reputation: 5067
I'm working on some ancient Delphi code and I've come across something which I don't quite understand.
[bla is set to 130245932]
outresult := ((bla * 1103516849) + 12359);
[outresult is equal to -413953101]
How does multiplying two positive numbers result in a negative number? And why is it that when I take the bla variable out of the equation and just use the integer directly (like this)
outresult := ((130245932 * 1103516849) + 12359);
I receive an error before the app even compiles
[DCC Error] Unit1.pas(60): E2099 Overflow in conversion or arithmetic operation
Some genius would be appreciated. Thanks.
Upvotes: 4
Views: 1299
Reputation: 4659
You're seeing an integer overflow, and I thought you might be curious about the specific result you saw.
Your initial multiplication
(130245932 * 1103516849) = 143728580475708268
...results in integer overflow, and in 32-bit math the resulting "wrap-around" generates:
(143728580475708268 mod 2^32) - 2^32 = -413965460
...and then your equation adds 12359:
-413965460 + 12359 = -413953101 (the result you saw, Q.E.D.)
Hope this helps
Upvotes: 2
Reputation: 471199
Alright, I'll make this an answer.
The error message should be pretty clear. You have an integer overflow here:
130245932 * 1103516849
because 130245932 * 1103516849 = 143728580475708268
which is too large to fit into a 32-bit integer.
Upvotes: 11
Reputation: 84540
It's based on the way memory is represented inside your system. Basically, you've only got 32 bits per integer. For a signed integer, one bit is used for the sign; this gives you a value range from negative to positive 2^31 (approximately 2 billion). If you go outside that range, the system breaks down.
If you need large integers, try using Int64
instead of integer
. If you need larger integers than that, check out the BigInteger
type in DeHL.
Upvotes: 6