What is the equivalent (in C#) of Java\'s >>> operator?
(Just to clarify, I\'m not referring to the >> and <<
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);
}
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);
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
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.
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);
}
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