简体   繁体   English

为什么我写同样的算法时c#中的代码与c中的代码不同?

[英]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.

相关问题 为什么当我使用 !!= C# 时代码会被编译 - Why does the code get compiled when I use !!= C# 我如何从C#编写汇编代码? - how do i write assembly code from c#? 当我从 C# 代码调用导入的 C++ 函数时,为什么会抛出 AccessViolationException? - Why is an AccessViolationException thrown when I call an imported C++ function from C# code? 从C#背后的代码编写样式 - Write style from code behind c# 为什么C#编译器从此代码创建PrivateImplementationDetails? - Why does the c# compiler create a PrivateImplementationDetails from this code? 为什么当我想通过 C# 运行 GAMS 代码时,visual studio 给我错误? - Why does visual studio gives me error when I want to run the GAMS code via C#? 为什么只有在C#中创建/运行表单时某些代码才起作用? - Why does some code only work when I create/run a form in C#? 为什么在我调用DataAdapter.Update()时此C#代码会生成语法错误? - Why does this C# code generate a Syntax Error when I call DataAdapter.Update()? 为什么我的 C# Xml 代码仅在我枚举变量可枚举时才有效 - Why does my C# Xml code only work when I enumerate variable enumerable 为什么javascript indexOf()方法在从C#代码隐藏调用时抛出错误? - Why does javascript indexOf() method throw error when called from C# code-behind?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM