Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a result larger than 2^32 from shl?

Declaration...

const
  n = 2 shl 33

will set constant n to value 4 without any compiler complaint!

Also...

Caption := IntToStr(2 shl 33);

...return 4 instead 8589934592. It looks like the compiler calculates like this:

2 shl 33 = 2 shl (33 and $1F) = 4

But without any warning or overflow.

The problem remains if we declare:

const
  n: int64 = 2 shl 33;

The number in constant is still 4 instead 8589934592.

Any reasonable work around?

like image 982
GJ. Avatar asked Nov 14 '11 20:11

GJ.


1 Answers

You're looking for the wrong results, according to both the Delphi compiler and Windows 7's calculator in programmer mode. (The answer you're wanting is actually 2 shl 32, BTW.)

You need to cast both sides of the shl to Int64:

const
  n = Int64(2) shl Int64(33);

This produces

N = 17179869184;

The current documentation (for XE2, but applies to earlier versions of Delphi as well) notes this in Fundamental Integer Types. However, that page mentions only having to cast one of the operands as Int64; my test shows it to require both operands be typecast in the const declaration above - typecasting only one (regardless of which one) also resulted in `n = 4;'.

like image 187
Ken White Avatar answered Oct 31 '22 14:10

Ken White