我怎样才能得到的结果比2 ^ 32从SHL更大? [英] How can I get a result larger than 2^32 from shl?

查看:155
本文介绍了我怎样才能得到的结果比2 ^ 32从SHL更大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明...

 常量
  N = 2 SHL 33
 

将设置不变 N 看重4没有任何编译器的投诉!

另外...

 图片说明:= I​​ntToStr(2 SHL 33);
 

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

  

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

但没有任何警告或溢流。

该问题仍然存在,如果我们声明:

 常量
  N:Int64的= 2 SHL 33;
 

在数量不变,仍然为4,而不是8589934592。

任何合理的变通?

解决方案

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

您需要转换 SHL 两侧的Int64

 常量
  N = Int64的(2)SHL的Int64(33);
 

这将产生

  N = 17179869184;
 

目前文档(为XE2,但适用于早期版本的Delphi以及)在便签本基本整数类型。然而,该页面只提到有投一个操作数为的Int64 ;我的测试表明它需要两个操作数的常量声明的类型强制转换上面 - 只有类型转换一(不管是哪一个),也导致`N = 4;

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?

解决方案

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

这篇关于我怎样才能得到的结果比2 ^ 32从SHL更大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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