计算C中结构的哈希值

时间:2016-07-20 16:04:21

标签: 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。

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

1 个答案:

答案 0 :(得分:0)

施放隐藏了@Eugene Sh.

指出的问题
// reinterpret_sol = (unsigned short*)&_sol;
reinterpret_sol = (unsigned short*) _sol;