changed
changed

Reputation: 2143

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

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

Upvotes: 31

Views: 25050

Answers (3)

Mez
Mez

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:

  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.

Upvotes: 1

Stephen Canon
Stephen Canon

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

John Knoeller
John Knoeller

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

Related Questions