有人能检查一下我是否正确地做了这个哈希

Can anyone please check if I am doing this hashing correctly

本文关键字:正确地 是否 哈希 一下 检查      更新时间:2023-10-16

我正在尝试做一个Fowler-Noll-Vo哈希函数的实现

伪代码看起来像这样

  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");
}

我在这里测试我的结果,我得到的结果是0d47307150c412cf

更新:

我将我的类型设置为

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

和我得到的结果fa365282a44c0ba7仍然不匹配的结果0 d47307150c412cf

有什么建议吗

根据官方参考
,您当前的结果fa365282a44c0ba7是正确的源代码(C)和手动计算…这使得测试站点错误。

参考源文件链接在这里:C文件和H文件
我删除了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("%llxn", 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 .
Ideone也这么说

这就是问题所在:

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会发生什么?