我目前正在转换一个Java程序。我通过字节移位操作符来。
我想知道>>>=操作符在C#中的意思。只是>>=吗?>>=在C#中移动标志了吗?
发布于 2020-07-03 06:56:19
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;
}
}为了提高可读性,我编写了这么长的代码,但是编译器很好地优化了这一点--例如,对于int版本:
.maxstack 8
ldarg.0
ldarg.1
ldc.i4.s 31
and
shr.un
ret( 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));https://stackoverflow.com/questions/62709877
复制相似问题