Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I perform an unsigned right shift (>>> in Java) in C/C++?

How do I perform an unsigned right shift (>>> in Java) in C/C++?

like image 948
changed Avatar asked Mar 11 '10 23:03

changed


People also ask

How does right shift work in C?

Right shift >>It shifts each bit in its left operand to the right. The number following the operator decides the number of places the bits are shifted (i.e. the right operand).

What is the difference between >> and >>> in Java?

>> is arithmetic shift right, >>> is logical shift right. In an arithmetic shift, the sign bit is extended to preserve the signedness of the number. For example: -2 represented in 8 bits would be 11111110 (because the most significant bit has negative weight).

What is << operator in Java?

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" 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.

What is the difference between right shift and unsigned right shift in Java?

The right shift operator in Java moves the bits of a value towards the right by the specified number of bits. In the signed right shift, the rightmost bit is discarded, and the leftmost bit is filled with the sign bit. In unsigned right shift, the rightmost bit is discarded, and the leftmost bit is filled with 0.


1 Answers

In C, to get an unsigned shift, you just do a shift on an unsigned type.

unsigned int result = (unsigned int)valueToBeShifted >> shiftAmount; 

Note that there is no guarantee that >> on a signed type gives you a signed shift in C -- this is implementation defined behavior. Most common implementations produce a signed shift if the type is signed, however.

like image 121
Stephen Canon Avatar answered Sep 20 '22 23:09

Stephen Canon