按位OR用于签名增强操作数 [英] Bitwise OR used for signature enhanced operand

查看:99
本文介绍了按位OR用于签名增强操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有这个片段,.net编译器输出上面提到的警告。



Hi,
I have this snippet where the .net compiler outputs the above mentioned warning.

private static int BitwiseRotate(int x, int c)
{
	var num = (uint) x;
	return (int) (x << c | num >> 32 - c);
}





如果可能的话,我会更正此信息以获取警告。我不想放置任何编译器提示来省略此警告。



我想这个警告是因左右移位而来,但我不知道是否铸造会丢失数据。所以,如果有人有一些建设性意见,那就太棒了。



提前谢谢。



If possible I would correct this to get no warning. I do not want to place any compiler hint to ommit this warning.

I guess this warning comes because of the left- and right shifts, but I do not know if casting would loose data. So if anyone has some constructive advice it would be great.

Thanks in advance.

推荐答案

问题在于num和c的类型...

c是一个int(有符号),其中num是uint(unsigned)所以num>> 32-c将强制编译器将num扩展为int(unsigned)并且警告的原因...
The problem is with the types of num and c...
c is a int (signed) where num is uint (unsigned) so num >> 32- c will force the compiler to extend num to int (unsigned) and that the reason for the warning...


使用num变量有什么好处? />


您的代码可缩短为:



What is the benefit of the use of the num variable?

Your code could be shortened to:

private static int BitwiseRotate(int x, int c) {
   return (x << c) | (x >> (32 - c));
}





无需在int和uint之间交叉演员。



我认为你首先遇到的问题是你忘记了一些括号:



No need to cross cast between int and uint.

I think the problem you had in the first place was that you forgot some parenthesis:

x >> 32 - c



应该是


should have been

x >> (32 - c)



因为右移运算符优先于减法运算;因此编译器理解


because the right-shift operator has precedence over subtraction; thus the compiler understood

(x >> 32) - c



它在逻辑上报告可能有问题。




希望这是有道理的。


which it logically reported as potentially problematic.


Hope this makes sense.


在C#中,移位运算符不合逻辑,如果操作数为负数,则移位1.



private static int BitwiseRotate(int x,int c)// rotate left

{

var num =(uint)x;

return(int)((num<< c)| num> ;>(32 - c));

}
In C#, shift operators are not logical and if operand is negative, shifts 1.

private static int BitwiseRotate(int x, int c) // rotate left
{
var num = (uint) x;
return (int) ((num << c) | num >> (32 - c));
}


这篇关于按位OR用于签名增强操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆