在C ++中的Shift运算符 [英] Shift Operators in C++

查看:315
本文介绍了在C ++中的Shift运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


如果移位运算符
之后的值大于
中左侧操作数的位数,则结果为
undefined。如果左边的操作数是
无符号,右移位是逻辑
移位,所以高位将用零填充
。如果左边的操作数
被签名,右移可能或可能
不是逻辑移位(即,
行为未定义)。

If the value after the shift operator is greater than the number of bits in the left-hand operand, the result is undefined. If the left-hand operand is unsigned, the right shift is a logical shift so the upper bits will be filled with zeros. If the left-hand operand is signed, the right shift may or may not be a logical shift (that is, the behavior is undefined).

有人可以解释一下上面这些行是什么意思?

Can somebody explain me what the above lines mean??

推荐答案

我假设你知道它的意思是通过移位。假设你正在处理一个8位的 char s

I'm assuming you know what it means by shifting. Lets say you're dealing with a 8-bit chars

unsigned char c;
c >> 9;
c >> 4;
signed char c;
c >> 4;

第一个转换,编译器可以随意做任何想要的,因为9> 8在 char ]中的位元。未定义的行为意味着所有的赌注都关闭,没有办法知道会发生什么。第二个移位是明确定义的。您在左侧得到0: 11111111 变为 00001111 。第三个移位,像第一个移位,未定义。

The first shift, the compiler is free to do whatever it wants, because 9 > 8 [the number of bits in a char]. Undefined behavior means all bets are off, there is no way of knowing what will happen. The second shift is well defined. You get 0s on the left: 11111111 becomes 00001111. The third shift is, like the first, undefined.

请注意,在第三种情况下, c 的值无关紧要。当它引用 signed 时,它表示变量的类型,而不是实际值是否大于零。 signed char c = 5 signed char c = -5 都签名,向右移动是未定义的行为。

Note that, in this third case, it doesn't matter what the value of c is. When it refers to signed, it means the type of the variable, not whether or not the actual value is greater than zero. signed char c = 5 and signed char c = -5 are both signed, and shifting to the right is undefined behavior.

这篇关于在C ++中的Shift运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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