How do I perform an unsigned right shift (>>> in Java) in C/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).
>> 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).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With