Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this bitwise shift-right appear not to work?

Could someone explain to me why the mask is not shifted to the right at all? You can use anything in place of that 1 and the result will be the same.

unsigned mask = ~0 >> 1;
printf("%u\n", mask);
like image 327
Ree Avatar asked Feb 24 '09 22:02

Ree


People also ask

How do you fix a right shift operator?

The right shift operator ( >> ) returns the signed number represented by the result of performing a sign-extending shift of the binary representation of the first operand (evaluated as a two's complement bit string) to the right by the number of bits, modulo 32, specified in the second operand.

How does bitwise right shift work?

The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted. The result is not an lvalue.

How does right shift operator work in Java?

The Right Shift Operator moves the bits of a number in a given number of places to the right. The >> sign represents the right shift operator, which is understood as double greater than. When you type x>>n, you tell the computer to move the bits x to the right n places.

What does >> mean in coding?

>> is the signed right shift operator. It shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. When you shift right two bits, you drop the two least significant bits.


1 Answers

It's a type issue. If you cast the 0 to unsigned it'll be fine:

unsigned mask = ~ (unsigned) 0 >> 1;
printf("%u\n", mask);

Edit per comments: or use unsigned literal notation, which is much more succinct. :)

unsigned mask = ~0u >> 1;
printf("%u\n", mask);
like image 115
chaos Avatar answered Sep 30 '22 12:09

chaos