2015-09-18 27 views
-2

我試圖做的Fowler–Noll–Vo hash function任何人都可以請檢查,如果我這樣做的散列正確

中的僞像這樣

hash = FNV_offset_basis 
    for each byte_of_data to be hashed 
     hash = hash × FNV_prime 
     hash = hash XOR byte_of_data 
    return hash 

實現這是我對於

uint8_t   byte_of_data; 
uint16_t   hash; 
uint16_t   FNV_offset_basis; 
uint16_t   FNV_prime; 
void computeHash(std::string p) 
{ 
    FNV_offset_basis = 0xcbf29ce484222325; 
    FNV_prime  = 0x100000001b3; 

    hash = FNV_offset_basis; 

    //Iterate through the string 
    for(int i=0 ; i<p.size();i++) 
    { 
     hash = hash * FNV_prime; 
     hash = hash^p.at(i); 
    } 

    std::cout << hash; //output 2983 
    std::cout << std::hex << hash ; //ba7 
} 
代碼

現在我正在使用它作爲此

int main() 
{ 
    computeHash("Hello"); 
} 

我測試我的結果here和我得到的結果作爲0d47307150c412cf

更新:

我固定我的類型

uint8_t   byte_of_data; 
uint64_t   hash; 
uint64_t   FNV_offset_basis; 
uint64_t   FNV_prime; 

,我得到的結果fa365282a44c0ba7仍然與結果不符 0d47307150c412cf

我如何能解決這個問題

+0

是否沒有發佈測試向量,您可以編寫單元測試? –

+1

a)您需要64位整數,而不是16 – deviantfan

+1

如果您的散列的類型爲'uint16_t',那麼您希望如何獲得64位長的結果? –

回答

0

您當前的結果fa365282a44c0ba7根據官方參考
源代碼(C)和手動計算過......這使得測試網站錯誤是正確的。

參考源文件被鏈接hereC fileH file
我除去包括longlong.h並加入下面的兩個代碼部分來代替:

/*before the reference code*/ 

#include <stdint.h> 
#define HAVE_64BIT_LONG_LONG 
typedef uint64_t u_int64_t; 
typedef uint32_t u_int32_t; 

/*after it*/ 

#include<stdio.h> 
int main() 
{ 
    printf("%llx\n", fnv_64_str("Hello", FNV1_64_INIT)); 
} 

,使其與編譯gcc -std=c11 source.c
gcc (i686-posix-sjlj-rev0, Built by MinGW-W64 project) 4.9.1

輸出:fa365282a44c0ba7
And Ideone says so too

+0

感謝您指出 –

0

這有什麼建議的問題是:

uint16_t   FNV_offset_basis; 
uint16_t   FNV_prime; 
void computeHash(std::string p) 
{ 
    FNV_offset_basis = 0xcbf29ce484222325; 
    FNV_prime  = 0x100000001b3; 

FNV_primeFNV_offset_basis是在你的代碼16位整數,但令人費解的,你要指定長度爲64位整數他們,你的C++編譯器應該警告你不正確的文字分配。

如果您將類型更改爲uint64_t,會發生什麼情況?

+0

而哈希變量也不只是這裏顯示的兩個變量。 – deviantfan

+0

是的,如果打算使用64位,則全部需要64位。 – rbaleksandar

+0

所以我改變類型爲'uint8_t byte_of_data; uint64_t hash; uint64_t FNV_offset_basis; uint64_t FNV_prime;'現在我得到結果fa365282a44c0ba7這仍然是不正確 –

相關問題