Strange Delphi Multiplication Behavior

I am working on some ancient Delphi code, and I came across something that I do not 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 does this happen when I take the bla variable from the equation and just use the integer directly (like this)

 outresult := ((130245932 * 1103516849) + 12359); 

I get an error before the application even compiles

 [DCC Error] Unit1.pas(60): E2099 Overflow in conversion or arithmetic operation 

Some geniuses will be appreciated. Thanks.

+4
source share
3 answers

OK, I will answer this question.

The error message should be pretty clear. Here you have integer overflow:

 130245932 * 1103516849 

because 130245932 * 1103516849 = 143728580475708268 , which is too large to fit in a 32-bit integer.

+11
source

It is based on how memory is represented inside your system. Basically, you only have 32 bits per integer. For a signed integer, one bit is used for the sign; this gives you a range of values ​​from negative to positive 2 ^ 31 (approximately 2 billion). If you go beyond this range, the system will break.

If you need large integers, try using Int64 instead of integer . If you need large integers, check out the BigInteger type in DeHL.

+6
source

You see an integer overflow, and I thought you might be interested to know about the specific result you saw.

Your initial multiplication

(130245932 * 1103516849) = 143728580475708268

... leads to overflow of integers, and in 32-bit math the result of "wrapping" generates:

(143728580475708268 mod 2 ^ 32) - 2 ^ 32 = -413965460

... and then your equation adds 12359:

-413965460 + 12359 = -413953101 (the result you saw is QED )

Hope this helps

+2
source

Source: https://habr.com/ru/post/1386617/


All Articles