C# 中按位桶移位左右旋转的问题
在 C++ 中我有这样的代码。
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)));
}
在 C# 中会是什么样子?我认为同样的方式......唯一的问题
错误 2 运算符 '>>'不能应用于“uint”和“uint”类型的操作数
错误 3 运算符 '>>'不能应用于“uint”和“uint”类型的操作数
错误 1 运算符“<<”不能应用于“uint”和“uint”类型的操作数
错误 4 运算符“<<”不能应用于“uint”和“uint”类型的操作数
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用
int
类型作为移位运算符中的右侧变量。You should use
int
type for the right side variable in shift operators.您必须将位移运算符的右侧强制转换为 int。如果您像
(int)(32 - bits)
那样进行强制转换,它应该不会影响您的预期目的。右侧只是期待一个 int,可能是因为这样更简单,并且您不太可能想要移动超过 20 亿位。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.正确的操作数必须始终是 int 类型。
The right operand must be always type int.
添加一些括号就可以了:
Add some parentheses and it works: