How do I perform an unsigned right shift (>>> in Java) in C/C++?
Asked
Active
Viewed 2.2k times
3 Answers
37
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.

Stephen Canon
- 103,815
- 19
- 183
- 269
22
>>>
is unsigned right shift, so I would think that in C this would be the same as
unsigned int foo;
unsigned int bar = foo >> whatever;

John Knoeller
- 33,512
- 4
- 61
- 92
1
In C++ doing a right shift on an unsigned value has identical behavior to doing a right shift on a signed value. If the MSB is set, then >> will shift in a 1.
unsigned int myInt = 0x80000000;
myInt >>= 1;
The result stored in myInt will be 0xC0000000
However, if the MSB is not set, a right shift on an unsigned value will work as it should.
unsigned int myInt = 0x40000000;
myInt >>= 1;
The result will be 0x20000000
So in order to get the desired behavior in C++, you could:
- Do a single shift, zero out the MSB, then do the remainder of the shifts.
- Right shift N bits, and zero out the top N bits.

Mez
- 11
- 1
-
That's not true... Left shift of unsigned and signed integers have identical behavior in C/C++, but right shift of unsigned and signed integers don't have. – Mika Lindqvist Jan 29 '23 at 02:25