如何从 shl 获得大于 2^32 的结果? [英] How can I get a result larger than 2^32 from shl?

查看:29
本文介绍了如何从 shl 获得大于 2^32 的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明...

const
  n = 2 shl 33

将常量 n 设置为值 4,没有任何编译器投诉!

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

还有...

Caption := IntToStr(2 shl 33);

...返回 4 而不是 8589934592.看起来编译器是这样计算的:

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

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

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;

常量中的数字仍然是 4 而不是 8589934592.

The number in constant is still 4 instead 8589934592.

有什么合理的解决方法吗?

Any reasonable work around?

推荐答案

根据 Delphi 编译器和 Windows 7 的程序员模式计算器,您正在寻找错误的结果.(你想要的答案实际上是 2 shl 32,顺便说一句.)

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.)

你需要将shl的两边都强制转换为Int64:

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

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

这会产生

N = 17179869184;

当前的文档(适用于 XE2,但也适用于 Delphi 的早期版本)在 <代码>基本整数类型.但是,该页面提到只需将操作数之一转换为 Int64;我的测试表明它要求在上面的 const 声明中对两个操作数进行类型转换 - 只类型转换一个(无论是哪个)也会导致 `n = 4;'.

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

这篇关于如何从 shl 获得大于 2^32 的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆