且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中的Shift运算符

更新时间:2023-11-10 09:15:10

我假设你知道它的意思是通过移位。假设你正在处理一个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.