我试图将一些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)
Java 中的语法>>>适用于无符号右移,这是一个必要的概念,因为 Java没有无符号整数的特定数据类型。
然而,C# 却可以;在 C# 中,您只需使用>>无符号类型ulong- 因此、uint、ushort、 -中的任何一个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)