Problem with Bitwise Barrel Shift Rotate left and right in C#

和自甴很熟 提交于 2019-12-02 06:48:55

问题


In C++ I have code like this.

    static UInt32 rol(UInt32 value, UInt32 bits)
    {
        bits &= 31;
        return ((value << bits) | (value >> (32 - bits)));
    }

    static UInt32 ror(UInt32 value, UInt32 bits)
    {
        bits &= 31;
        return ((value >> bits) | (value << (32 - bits)));
    }

how would it look in C#? I think the same exact way.. only problem

Error 2 Operator '>>' cannot be applied to operands of type 'uint' and 'uint'
Error 3 Operator '>>' cannot be applied to operands of type 'uint' and 'uint'
Error 1 Operator '<<' cannot be applied to operands of type 'uint' and 'uint'
Error 4 Operator '<<' cannot be applied to operands of type 'uint' and 'uint'


回答1:


You should use int type for the right side variable in shift operators.




回答2:


You will have to cast the right side of the bitshift operator to int. If you cast like (int)(32 - bits), it should not affect your intended purpose. The right side is just expecting an int, probably because it's simpler that way and highly unlikely you'll ever want to shift more than 2 billion bits.




回答3:


The right operand must be always type int.

 int x << int bits
 uint x << int bits
 long x << int bits
 ulong x << int bits


来源:https://stackoverflow.com/questions/7289316/problem-with-bitwise-barrel-shift-rotate-left-and-right-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!