I am trying to convert some Java code to C#. How can the following unsigned right shift operation be represented in C#?
int src1, src2, ans;
ans = src1 >&
C#'s >>
operator is sensitive to the operator's signed status (int
vs uint
). If you need to operate on an int
, cast to uint
first.
I think it's just >> whether it is signed or not depends on whether it is an int/long or uint/ulong, so you would have to cast as necessary
you can use this method instead operator >>>
.
int src1, src2, ans;
ans = rightMove(src1 , src2);
int rightMove(int value, int pos)
{
if (pos != 0)
{
int mask = 0x7fffffff;
value >>= 1;
value &= mask;
value >>= pos - 1;
}
return value;
}
You have to cast first, there is not one operator for >>>, code sample:
int x = -100;
int y = (int)((uint)x >> 2);
Console.WriteLine(y);
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.
However, C# does; 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.
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;
}
}