什么是Java无符号右移运算符的C#等价物>>>

bli*_*egz 19 c#

我试图将一些Java代码转换为C#.如何在C#中表示以下无符号右移操作

int src1, src2, ans;
ans = src1 >>> src2;
Run Code Online (Sandbox Code Playgroud)

Pet*_*ter 18

您必须首先进行投射,没有一个运算符用于>>>,代码示例:

 int x = -100;
 int y = (int)((uint)x >> 2);
 Console.WriteLine(y);
Run Code Online (Sandbox Code Playgroud)


God*_*eke 8

C#的>>运营商对运营商的签名状态(intvs uint)很敏感.如果你需要操作int,先铸造unit.


Mar*_*ell 6

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

然而,C# 却可以;在 C# 中,您只需使用>>符号类型ulong- 因此、uintushort、 -中的任何一个byte,它将执行预期的“用零填充 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)


Ben*_*son 5

我认为这只是>>是否签名取决于它是int / long还是uint / ulong,因此您必须根据需要进行强制转换