[英]Can anyone please check if I am doing this hashing correctly
I am trying to do an implementation of Fowler–Noll–Vo hash function我正在尝试实现Fowler–Noll–Vo 哈希函数
The Pseudocode looks like this伪代码看起来像这样
hash = FNV_offset_basis
for each byte_of_data to be hashed
hash = hash × FNV_prime
hash = hash XOR byte_of_data
return hash
This is my code for that这是我的代码
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
}
Now I am using it as this现在我用它作为这个
int main()
{
computeHash("Hello");
}
I am testing my result here and I get the result as 0d47307150c412cf我在这里测试我的结果,我得到的结果为0d47307150c412cf
Update:更新:
I fixed my types to我修复了我的类型
uint8_t byte_of_data;
uint64_t hash;
uint64_t FNV_offset_basis;
uint64_t FNV_prime;
and I get the result fa365282a44c0ba7 which still does not match the result 0d47307150c412cf我得到的结果 fa365282a44c0ba7 仍然与结果 0d47307150c412cf 不匹配
Any suggestions on how I can fix this关于如何解决此问题的任何建议
This is the problem:这就是问题:
uint16_t FNV_offset_basis;
uint16_t FNV_prime;
void computeHash(std::string p)
{
FNV_offset_basis = 0xcbf29ce484222325;
FNV_prime = 0x100000001b3;
FNV_prime
and FNV_offset_basis
are both 16-bit integers in your code, yet inexplicably you're assigning long 64-bit integers to them, your C++ compiler should be warning you about an improper literal assignment. FNV_prime
和FNV_offset_basis
在您的代码中都是 16 位整数,但您莫名其妙地为它们分配了 64 位长整数,您的 C++ 编译器应该警告您不正确的文字分配。
What happens if your change the types to uint64_t
?如果您将类型更改为
uint64_t
会发生什么?
Your current result fa365282a44c0ba7
is correct according to the official reference根据官方参考,您当前的结果
fa365282a44c0ba7
是正确的
source code (in C) and manual calculation too... this makes the test site wrong.源代码(在 C 中)和手动计算也是......这使得测试站点错误。
The reference source files are linkedhere : C file and H file参考源文件链接在这里: C文件和H文件
I removed the includes of longlong.h
and added following two code parts instead:我删除了
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));
}
to make it compile with gcc -std=c11 source.c
让它用
gcc -std=c11 source.c
编译
( gcc (i686-posix-sjlj-rev0, Built by MinGW-W64 project) 4.9.1
) (
gcc (i686-posix-sjlj-rev0, Built by MinGW-W64 project) 4.9.1
)
Output: fa365282a44c0ba7
.输出:
fa365282a44c0ba7
。
And Ideone says so too Ideone 也这么说
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.