什么是 >>>= 来自 C# 中的 Java

Pat*_*gel 2 c# java

我目前正在转换 Java 程序。我来自字节移位运算符。

我想知道>>>=运算符在 C# 中的含义。只是>>=吗?是否>>=在 C# 中移动符号?

Mar*_*ell 5

>>>Java 中的语法用于无符号右移,这是一个必要的概念,因为 Java没有用于 unsigned integers 的特定数据类型

但是,C# 确实如此;在C#中,你只需要使用>>带有无符号类型-因此,任何的ulonguintushortbyte-它会“零填补MSB”的行为进行预期的,因为那是什么>> 的无符号整数,即使输入MSB是集.

如果您不想更改代码以始终使用无符号类型,则可以使用扩展方法:

public static int UnsignedRightShift(this int signed, int places)
{
    unchecked // just in case of unusual compiler switches; this is the default
    {
        var unsigned = (uint)signed;
        unsigned >>= places;
        return (int)unsigned;
    }
}
public static long UnsignedRightShift(this long signed, int places)
{
    unchecked // just in case of unusual compiler switches; this is the default
    {
        var unsigned = (ulong)signed;
        unsigned >>= places;
        return (long)unsigned;
    }
}
Run Code Online (Sandbox Code Playgroud)

我写了这篇长篇大论以提高可读性,但编译器对此进行了很好的优化 - 例如对于int版本:

.maxstack 8

ldarg.0
ldarg.1
ldc.i4.s 31
and
shr.un
ret
Run Code Online (Sandbox Code Playgroud)

long版本的唯一区别是它用63而不是31

它们可以更简洁地写为:

public static int UnsignedRightShift(this int signed, int places)
    => unchecked((int)((uint)signed >> places));
public static long UnsignedRightShift(this long signed, int places)
    => unchecked((long)((ulong)signed >> places));
Run Code Online (Sandbox Code Playgroud)