Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange Delphi integer multiplication behavior

Tags:

math

delphi

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.

like image 410
NoPyGod Avatar asked Dec 01 '22 01:12

NoPyGod


2 Answers

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.

like image 82
Mysticial Avatar answered Dec 04 '22 11:12

Mysticial


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.

like image 45
Mason Wheeler Avatar answered Dec 04 '22 12:12

Mason Wheeler