Equivalent of Java triple shift operator (>>>) in C#?

15,908

Solution 1

In C#, you can use unsigned integer types, and then the << and >> do what you expect. The MSDN documentation on shift operators gives you the details.

Since Java doesn't support unsigned integers (apart from char), this additional operator became necessary.

Solution 2

Java doesn't have an unsigned left shift (<<<), but either way, you can just cast to uint and shfit from there.

E.g.

(int)((uint)foo >> 2); // temporarily cast to uint, shift, then cast back to int

Solution 3

n >>> s in Java is equivalent to TripleShift(n,s) where:

    private static long TripleShift(long n, int s)
    {
        if (n >= 0)
            return n >> s;
        return (n >> s) + (2 << ~s);
    }

Solution 4

Upon reading this, I hope my conclusion of use as follows is correct. If not, insights appreciated.

Java

i >>>= 1;

C#:

i = (int)((uint)i >> 1);

Solution 5

There is no >>> operator in C#. But you can convert your value like int,long,Int16,Int32,Int64 to unsigned uint, ulong, UInt16,UInt32,UInt64 etc.

Here is the example.

    private long getUnsignedRightShift(long value,int s)
    {
        return (long)((ulong)value >> s);
    }
Share:
15,908
Nikolaos
Author by

Nikolaos

Updated on June 03, 2022

Comments

  • Nikolaos
    Nikolaos almost 2 years

    What is the equivalent (in C#) of Java's >>> operator?

    (Just to clarify, I'm not referring to the >> and << operators.)

  • Will
    Will over 14 years
    Java doesn't? or C# doesn't?
  • Matt
    Matt over 14 years
    C# doesn't have any 'unsigned shift' operators. Java has an unsigned RIGHT shift, but not an unsigned LEFT shift.
  • Nikolaos
    Nikolaos over 14 years
    +1 Thanks for your input on this. Will keep it in mind for when I am forced to use signed types.
  • dan04
    dan04 about 14 years
    There's no need for <<< because sign-extension isn't relevant for left shifts.
  • AgentKnopf
    AgentKnopf almost 12 years
    Just to get this straight - the Java equivalent of the C# operation 1 << 4 would be (int)((uint)1 >> 4); ??
  • Ponni Radhakrishnan
    Ponni Radhakrishnan about 9 years
    @Sebastien Lebreton i had not seen your solution before posting this
  • NightOwl888
    NightOwl888 over 4 years
    Head to head testing reveals this approach doesn't match Java for long, but does for smaller integral types.