等效于 C# 中的 Java 三重移位运算符 (>>>)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1880172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 18:20:41  来源:igfitidea点击:

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

c#javabitwise-operators

提问by Nikolaos

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

Java>>>运算符的等价物(在 C# 中)是什么?

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

(只是为了澄清,我不是指>><<运营商。)

采纳答案by Lucero

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

在C#中,你可以使用无符号整数类型,然后<<>>你的期望。有关班次运算符MSDN 文档为您提供了详细信息。

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

由于 Java 不支持无符号整数(除了char),这个额外的运算符就变得必要了。

回答by Matt

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

Java 没有无符号左移 ( <<<),但无论哪种方式,您都可以uint从那里强制转换和 shfit。

E.g.

例如

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

回答by KeithC

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

阅读本文后,我希望我的以下使用结论是正确的。如果没有,见解赞赏。

Java

爪哇

i >>>= 1;

C#:

C#:

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

回答by Sebastien Lebreton

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

Java 中的 n >>> s 等价于 TripleShift(n,s) 其中:

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

回答by Musakkhir Sayyed

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.

C# 中没有 >>> 运算符。但是您可以将 int,long,Int16,Int32,Int64 等值转换为无符号 uint、ulong、UInt16、UInt32、UInt64 等。

Here is the example.

这是示例。

    private long getUnsignedRightShift(long value,int s)
    {
        return (long)((ulong)value >> s);
    }

回答by Charles Okwuagwu

For my VB.Netfolks

对于我的VB.Net乡亲

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

上面的建议答案会给你溢出异常 Option Strict ON

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

例如,-100 >>> 2使用上述解决方案尝试此操作:

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