Skip to content

Unsigned right shift operator C# 11.0performancecode reduction

Shift the bits of a integer to the right ignoring the sign.

The signed right shift >> available on earlier versions of .NET preserves the sign bit when shifting right meaning that negative numbers remain negative.

The new unsigned right shift >>> shifts the bits to the right and fills the left bits with zeroes in the same way that << shifts bits to the left and fills the right bits with zeroes.

Code

C#
int val = -64;                   // 0b11111111_11111111_11111111_11000000 (-64)

// Binary right shift by 3 bits

int b = val >>> shift            // 0b00011111_11111111_11111111_11111000 (536870904)
C#
int val = -64;                   // 0b11111111_11111111_11111111_11000000 (-64)

// Binary right shift by 3 bits
int mask = ~(int.MaxValue << (32 - 3));
int b = (val >> 3) & mask;       // 0b00011111_11111111_11111111_11111000 (536870904)

Notes

  • Positive values shifted with >>> have the same result as if shifted by >>
  • The right hand operand no longer needs to be an int or implicitly convertible to an int

More information