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

夙愿已清 提交于 2019-12-08 21:38:46

问题


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?


回答1:


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;'.



来源:https://stackoverflow.com/questions/8127693/how-can-i-get-a-result-larger-than-232-from-shl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!