[英]Why does the code in c# differs from the code in c when I write the same algorithm?
Function in C C 中的函数
unsigned long int ROTL(unsigned long int x, unsigned long int y)
{
return ((x) << (y&(32 - 1))) | ((x) >> (32 - (y&(32 - 1))));
}
Function in C# C#中的函数
uint ROTL(uint x, uint y)
{
return ((x) << (int)(y & (32 - 1))) | ((x) >> (int)(32- (y & (32 - 1))));
}
above functions do the same work and the same result for small numbers, but when I pass large numbers the result in C# differ from C.上述函数对小数执行相同的工作和相同的结果,但是当我传递大数时,C# 中的结果与 C 不同。
Is there any problem in casting or in the function itself?铸造或函数本身有什么问题吗? Also I try to convert using
我也尝试使用转换
Convert.ToInt32()
Assuming unsigned long int
translates to a unsigned 64bit integer you want to maybe go with C#s ulong
instead of uint
.假设
unsigned long int
转换为无符号的 64 位整数,您可能希望使用 C#s ulong
而不是uint
。
The main problem there is not the cast to int
of the y-parameter, since it only takes the last 5 bits anyway.主要问题不是 y 参数的
int
,因为它只需要最后 5 位。 But when x is of type uint
a bitshift with (worst case) 31 places exceeds its limits by far.但是,当 x 是
uint
类型时,(最坏情况)31 个位置的位移远远超出了它的限制。 Casting and returning it to ulong
could do the trick.铸造并将其返回给
ulong
可以解决问题。
ulong ROTL(uint x, uint y)
{
return (((ulong)x) << (int)(y & (32 - 1))) | (((ulong)x) >> (int)(32 - (y & (32 - 1))));
}
Please note, that I did not test this throughly, but only did some boundary tests: https://dotnetfiddle.net/0ETAEL请注意,我没有对此进行彻底测试,只是做了一些边界测试: https : //dotnetfiddle.net/0ETAEL
EDIT: When you expect the results to be bigger than 2^64 (or as Parameter values: ROTL(uint.MaxValue, 31)
) you should consider having a look at BigInteger .编辑:当您希望结果大于 2^64(或作为参数值:
ROTL(uint.MaxValue, 31)
)时,您应该考虑查看BigInteger 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.