[英]What is >>>= from Java in C#
I am currently converting a Java Program.我目前正在转换一个 Java 程序。 And I come by the byte shift operator.我是通过字节移位运算符来的。
I'd like to know what the >>>=
operator means in C#.我想知道>>>=
运算符在 C# 中的含义。 Is it just >>=
?只是>>=
吗? Does >>=
shift the sign in C#? >>=
是否移动 C# 中的符号?
The >>>
syntax in Java is for unsigned right shifts, which is necessary as a concept because Java doesn't have a specific data type for unsigned integers . Java 中的>>>
语法用于无符号右移,这是一个必要的概念,因为 Java没有无符号整数的特定数据类型。
However, C# does;但是,C# 可以; in C#, you would just use >>
with an unsigned type - so any of ulong
, uint
, ushort
, byte
- and it will perform the expected "fill the MSB with zero" behavior, because that is what >>
does on unsigned integers, even if the input MSB is set.在 C# 中,您只需将>>
与无符号类型一起使用 - 因此ulong
、 uint
、 ushort
、 byte
中的任何一个 - 它将执行预期的“用零填充 MSB”行为,因为这就是>>
对无符号整数所做的, 即使设置了输入 MSB。
If you don't want to change the code to use unsigned types throughout, you can probably use an extension method:如果您不想更改代码以始终使用无符号类型,则可以使用扩展方法:
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;
}
}
I've written this long-hand for readability, but the compiler optimizes this pretty well - for example for the int
version:为了可读性,我写了这个长手,但编译器对此进行了很好的优化 - 例如对于int
版本:
.maxstack 8
ldarg.0
ldarg.1
ldc.i4.s 31
and
shr.un
ret
(the only difference in the long
version is that it masks with 63
instead of 31
) ( long
版本的唯一区别是它用63
而不是31
屏蔽)
They can be written more tersely as:它们可以更简洁地写成:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.