When does the right shift operation >> shift the bit sign, and when not?

My question is why the a>>1bit sign is a shift, but not (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
+4
source share
1 answer

a >> 1is boring. This is just an implementation defined for the type signedfor negative a.

(a & 0xaaaaaaaa) >> 1more interesting. For the likely case that you have 32-bit int(among others), 0xaaaaaaaathis is a literal unsigned(a fuzzy hexadecimal rule). Therefore, due to the promotion rules of type C ++, it is aalso converted to a type unsigned, and therefore the type of the expression is a & 0xaaaaaaaa<< 26>.

Makes a good quiz question in the pub.

: http://en.cppreference.com/w/cpp/language/integer_literal, " ".

+8

Source: https://habr.com/ru/post/1678172/


All Articles