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

前端 未结 6 2077
轻奢々
轻奢々 2020-12-15 17:10

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

(Just to clarify, I\'m not referring to the >> and <<

相关标签:
6条回答
  • 2020-12-15 17:15

    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);
        }
    
    0 讨论(0)
  • 2020-12-15 17:19

    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);
    
    0 讨论(0)
  • 2020-12-15 17:19

    For my VB.Net folks

    The suggested answers above will give you overflow exceptions with Option Strict ON

    Try this for example -100 >>> 2 with above solutions:

    The following code works always for >>>

    Function RShift3(ByVal a As Long, ByVal n As Integer) As Long
            If a >= 0 Then
                Return a >> n
            Else
                Return (a >> n) + (2 << (Not n))
            End If
    End Function
    
    0 讨论(0)
  • 2020-12-15 17:21

    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.

    0 讨论(0)
  • 2020-12-15 17:27

    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);
        }
    
    0 讨论(0)
  • 2020-12-15 17:38

    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
    
    0 讨论(0)
提交回复
热议问题