簡體   English   中英

為什么我寫同樣的算法時c#中的代碼與c中的代碼不同?

[英]Why does the code in c# differs from the code in c when I write the same algorithm?

C 中的函數

unsigned long int ROTL(unsigned long int x, unsigned long int  y)
    {
        return ((x) << (y&(32 - 1))) | ((x) >> (32 - (y&(32 - 1))));
    }

C#中的函數

 uint ROTL(uint x, uint y) 
   { 
       return ((x) << (int)(y & (32 - 1))) | ((x) >> (int)(32- (y & (32 - 1)))); 
   }

上述函數對小數執行相同的工作和相同的結果,但是當我傳遞大數時,C# 中的結果與 C 不同。

鑄造或函數本身有什么問題嗎? 我也嘗試使用轉換

Convert.ToInt32()

假設unsigned long int轉換為無符號的 64 位整數,您可能希望使用 C#s ulong而不是uint

主要問題不是 y 參數的int ,因為它只需要最后 5 位。 但是,當 x 是uint類型時,(最壞情況)31 個位置的位移遠遠超出了它的限制。 鑄造並將其返回給ulong可以解決問題。

ulong ROTL(uint x, uint y) 
{ 
    return (((ulong)x) << (int)(y & (32 - 1))) | (((ulong)x) >> (int)(32 - (y & (32 - 1)))); 
}

請注意,我沒有對此進行徹底測試,只是做了一些邊界測試: https : //dotnetfiddle.net/0ETAEL

編輯:當您希望結果大於 2^64(或作為參數值: ROTL(uint.MaxValue, 31) )時,您應該考慮查看BigInteger

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM