30

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

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
changed
  • 2,103
  • 8
  • 36
  • 56

3 Answers3

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:

  1. Do a single shift, zero out the MSB, then do the remainder of the shifts.
  2. 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