[英]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
. 它只是针对负数
a
的signed
类型定义的实现。
(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.