2012-01-04 61 views
1

DJBX33X哈希函數如何在C#中實現?在C.C#中的DJBX33X哈希函數#

uint32_t hash(const char *arKey, uint32_t nKeyLength) 
{ 
    uint32_t hash = 5381; 

    for (; nKeyLength > 0; nKeyLength -=1) 
    { 
     hash = ((hash << 5) + hash)^*arKey++; 
    } 

    return hash; 
} 

這個函數下面是代碼修訂這裏是我到目前爲止的代碼,但是從C和C#函數的結果是不同的,沒有我錯過了什麼?

public static long hash(string str) 
{   
    long hash = 5381; 

    for (int i = 0; i < str.Length; i++) 
    { 
     hash = ((hash << 5) + hash)^(int)str[i]; 
    } 

    return hash; 
} 

更新2以下爲C的outpus和C#

C# 

t = 116(<<172192+177573) -> 177617 
t = 116(<<5683744+5861361) -> 5861253 
u = 117(<<187560096+193421349) -> 193421392 
U = 85(<<6189484544+6382905936) -> 6382905861 
'ttuU' => '6382905861' 

C 

t = 116 (<<172192+177573) -> 177617 
t = 116 (<<5683744+5861361) -> 5861253 
u = 117 (<<187560096+193421349) -> 193421392 
U = 85 (<<1894517248+2087938640) -> 2087938565 
'ttuU' -> '2087938565' 
+1

你嘗試過這麼遠嗎?我沒有看到任何特別困難的C#完成給定的C代碼... – aardvarkk 2012-01-04 15:47:55

回答

2

這是有可能的數據類型是哈希執行很重要;你必須參考文檔,一個確切的答案,但是這個函數產生的結果你期待:

public static uint Hash(string str) 
{ 
    uint result = 5381; 

    for (int i = 0; i < str.Length; i++) 
    { 
     result = ((result << 5) + result)^str[i]; 
    } 

    return result; 
} 

輸出示例:

Hash("ttuU") -> 2087938565 
+0

是的我認爲你是正確的溢出是這個功能設計的一部分。 – 2012-01-06 06:59:39