What is the equivalent (in C#) of Java's >>>
operator?
(Just to clarify, I'm not referring to the >>
and <<
ope开发者_如何学Crators.)
Edit: The Unsigned right-shift operator >>> is now also available in C# 11 and later.
For earlier C# versions, 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.
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
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);
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);
}
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);
}
C# 11 and later supports >>>
Unsigned right shift operator
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/bitwise-and-shift-operators#unsigned-right-shift-operator-
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
精彩评论