有人能检查一下我是否正确地做了这个哈希
Can anyone please check if I am doing this hashing correctly
我正在尝试做一个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)和手动计算…这使得测试站点错误。
我删除了
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_prime
和FNV_offset_basis
在你的代码中都是16位整数,然而你莫名其妙地给它们赋了64位长整数,你的c++编译器应该警告你不正确的文字赋值。
如果您将类型更改为uint64_t
会发生什么?
相关文章:
- 如何正确地将分支添加到已存在的树中
- 如何正确地将带有指针的数组传递给函数
- 如何正确地推回然后遍历堆中对象的向量?
- 我是否不正确地集中了这些字符数组?
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 我怎样才能通过友谊正确地履行我的职能?
- C++:如何正确地将 deque::front() 返回的变量从函数中传递出去?
- 我是否正确地将PCWSTR指向字符串文字
- 在多继承编译器的情况下访问成员变量是否依赖?如何正确地做
- 我是否正确地为 2D 数组添加了行与列
- 我是否正确地将枚举值与C++的"or"运算符进行比较?
- 我是否正确地将嵌套的 lua 表作为 C 函数的参数
- 编译器是否应该正确地将布尔中的任意非零值解释为true
- 是否有一种方法可以正确地比较一个float值是否大于/小于另一个
- 有人能检查一下我是否正确地做了这个哈希
- 我是否正确地指定了立方体映射的坐标
- 如何正确地从字符数组中删除字符(是否转换为字符串)
- 我是否正确地将局部空间转换为世界空间坐标
- 在c++中是否正确地将两个无符号32位整数合并为一个无符号64位整数?
- 我是否正确地使用了move语义?好处是什么?