What is the C# equivalent of Java unsigned right shift operator >>>

前端 未结 5 2177
轮回少年
轮回少年 2020-12-07 00:32

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 >&         


        
相关标签:
5条回答
  • 2020-12-07 01:01

    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.

    0 讨论(0)
  • 2020-12-07 01:01

    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

    0 讨论(0)
  • 2020-12-07 01:10

    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;
            }
    
    0 讨论(0)
  • 2020-12-07 01:11

    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);
    
    0 讨论(0)
  • 2020-12-07 01:15

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题