Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

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
like image 266
hjklemacs Avatar asked Feb 05 '23 09:02

hjklemacs


1 Answers

a >> 1 is boring. It's simply implementation defined for a signed type for negative a.

(a & 0xaaaaaaaa) >> 1 is more interesting. For the likely case of your having a 32 bit int (among others), 0xaaaaaaaa is an unsigned literal (obscure rule of a hexadecimal literal). 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.

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.

like image 172
Bathsheba Avatar answered Feb 09 '23 00:02

Bathsheba