Reputation: 2143
How do I perform an unsigned right shift (>>> in Java) in C/C++?
Upvotes: 31
Views: 25050
Reputation: 11
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:
Upvotes: 1
Reputation: 106197
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.
Upvotes: 39
Reputation: 34148
>>>
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;
Upvotes: 22