正确的转变 [英] right shifting

查看:75
本文介绍了正确的转变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有愚蠢的代码,


main()

{

unsigned int i = 34;

i>> = 32;

}


为什么我的价值仍为34?我认为它应该是零。

(g ++编译器给我一个关于移动> =变量大小的警告。)

if I have the foolowing code,

main()
{
unsigned int i=34;
i>>=32;
}

why does the value of i remain 34? I thought it should be a zero.
(the g++ compiler gives me a warning about shifting >= size of variable.)

推荐答案

crookie写道:
crookie wrote:

如果我有愚蠢的代码,


main()

{

unsigned int i = 34;

i>> = 32;

}

为什么我的价值仍为34?我认为它应该是零。

(g ++编译器给我一个关于移位> =变量大小的警告。)
if I have the foolowing code,

main()
{
unsigned int i=34;
i>>=32;
}

why does the value of i remain 34? I thought it should be a zero.
(the g++ compiler gives me a warning about shifting >= size of variable.)



关于班次操作员的标准[5.8 / 1]说:


[...]如果右操作数为负数,则行为未定义,或者

大于或等于提升的左操作数的位长度。


看来你的平台上的sizeof(int)< = 32,你有没有

未定义的行为:任何事情都可能发生。

Best


Kai-Uwe Bux

The standard [5.8/1] says about the shift operators:

[...] The behavior is undefined if the right operand is negative, or
greater than or equal to the length in bits of the promoted left operand.

It would appear that on your platform sizeof(int)<=32, whence you have
undefined behavior: anything could happen.
Best

Kai-Uwe Bux


crookie写道:
crookie wrote:

如果我有愚蠢的代码,


main()

{

unsigned int i = 34;

i>> = 32;

}


为什么我的价值仍然是34?我认为它应该是零。

(g ++编译器给我一个关于移位> =变量大小的警告。)
if I have the foolowing code,

main()
{
unsigned int i=34;
i>>=32;
}

why does the value of i remain 34? I thought it should be a zero.
(the g++ compiler gives me a warning about shifting >= size of variable.)



因为在你的系统上,unsigned int有32位或更少的位,并且(最近学到的是
)移位任何大于或等于

位数的数字是未定义的行为。这意味着i

的任何价值同样有效。


欲了解更多细节,请在夏天看到这个帖子:
http://tinyurl.com/y382v3


祝你好运,


Tom

Because on your system, an unsigned int has 32 or fewer bits, and (as I
recently learned) shifting by any number greater than or equal to the
number of bits is Undefined Behavior. Which means that any value of i
is equally valid.

For more detail, see this thread from over the summer:

http://tinyurl.com/y382v3

Best regards,

Tom


这篇关于正确的转变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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