在C中计算结构的哈希值

标签 c hash struct

我有一个用 C 定义的结构体,如下所示

typedef struct {
    unsigned int size;
    unsigned int pool_size;
    route _routes[SIZE_OF_FLEET];
    request _request_pool[SIZE_OF_PROBLEM];
    /* stores which request is contained in which route */
    unsigned int _request_map[SIZE_OF_PROBLEM];
} solution;

我正在尝试为这个结构定义一个散列函数,如下所示

unsigned long long solution_hash(solution const *_sol)
{
    unsigned long long hash = 0;
    unsigned short c;
    unsigned short *reinterpret_sol;
    reinterpret_sol = (unsigned short*)&_sol;
    size_t size_ = sizeof(solution);
    size_t elem_size_ = sizeof(unsigned short);
    int len = (int)size_/elem_size_;

    for (int i = 0; i < len; i++) {
        c = reinterpret_sol[i];
        hash += c;
    }
    return hash;
}

问题是每次调用 solution_hash 函数时,相同解决方案的哈希值都会发生变化。对于同一解决方案,连续调用将值增加 32。

这段代码有什么问题?有没有更好的方法来为结构体实现哈希函数?

最佳答案

Casting 隐藏了 @Eugene Sh. 指出的问题

// reinterpret_sol = (unsigned short*)&_sol;
reinterpret_sol = (unsigned short*) _sol;

关于在C中计算结构的哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38485502/

相关文章:

c - "Trace/breakpoint trap (core dumped)"在汇编中除以负值时出错

c - C 语言的基本暴力破解程序

ruby-on-rails - 列出给定语言的所有翻译 yml 键

ruby - 如何在 ruby​​ 中动态设置嵌套哈希?

javascript - 将 PHP hash_hmac(sha512) 转换为 NodeJS

c - 如何获取内存位置的对象?

无法通过 cmake : Cannot open include file: 'zlib.h' : No such file or directory 在 Windows 上编译 libpng 1.6

c - BLOB,它是如何工作的

arrays - 为什么我不能将元素附加到结构?

c++ - public/private/protected 是否会改变结构在内存中的排列?