简体   繁体   English

右移操作>>移位符号位和何时不移位?

[英]When right shift operation >> shift sign bit and when it not?

My question is why a>>1 shift sign bit, but not (a & 0xaaaaaaaa) >> 1 ? 我的问题是为什么a>>1移位符号位,但不是(a & 0xaaaaaaaa) >> 1

Code snippet 代码段

int a = 0xaaaaaaaa;
std::cout << sizeof(a) << std::endl;
getBits(a);
std::cout << sizeof(a>>1) << std::endl;
getBits(a >> 1);
std::cout << sizeof(a & 0xaaaaaaaa) << std::endl;
getBits(a & 0xaaaaaaaa);
std::cout << sizeof((a & 0xaaaaaaaa)>>1) << std::endl;
getBits((a & 0xaaaaaaaa) >> 1);

result 结果

4
10101010101010101010101010101010
4
11010101010101010101010101010101
4
10101010101010101010101010101010
4
01010101010101010101010101010101

a >> 1 is boring. a >> 1很无聊。 It's simply implementation defined for a signed type for negative a . 它只是针对负数asigned类型定义的实现。

(a & 0xaaaaaaaa) >> 1 is more interesting. (a & 0xaaaaaaaa) >> 1更有趣。 For the likely case of your having a 32 bit int (among others), 0xaaaaaaaa is an unsigned literal (obscure rule of a hexadecimal literal). 对于你有32位int (以及其他)的可能情况, 0xaaaaaaaa是一个unsigned文字(十六进制文字的模糊规则)。 So due to C++ type promotion rules a is converted to an unsigned type too, and the type of the expression a & 0xaaaaaaaa is therefore unsigned . 因此,由于C ++类型提升规则a被转换为unsigned类型,因此表达式a & 0xaaaaaaaa的类型是unsigned

Makes a nice question for the pub quiz. 为酒吧测验提出了一个很好的问题。

Reference: http://en.cppreference.com/w/cpp/language/integer_literal , especially the "The type of the literal" table. 参考: http//en.cppreference.com/w/cpp/language/integer_literal ,特别是“文字的类型”表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM