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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With