28

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

Ricardo Altamirano
  • 13,752
  • 21
  • 69
  • 104
changed
  • 2,023
  • 7
  • 35
  • 54

2 Answers2

34

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
  • 100,816
  • 18
  • 175
  • 263
20

>>> 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
  • 32,385
  • 4
  • 57
  • 92