接近完美或完美的内存地址哈希值

时间:2012-07-26 20:06:16

标签: c perfect-hash

我有一个从0xc0003000到0xc04a0144的内存地址列表,有很多间隙和<列表中有4096个条目。它在编译时就知道了,我想为它做一个完美的哈希。

然而,在网上查找完美哈希给我的信息主要与哈希字符串相关,而且它们似乎没有很好的翻译。

要清楚我希望能够在运行时获取内存地址并检查它是否在哈希中。目前我正在使用二进制搜索,平均大约有8个循环来找到答案。

任何想法我应该吠叫什么树?

1 个答案:

答案 0 :(得分:3)

这是一个示例gperf程序。我在样本数据中包含了NUL和换行符,以证明它们不会导致失败。

%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <arpa/inet.h>
%}
%%
"\xc0\x01\x02\x03"
"\xc0\xff\xff\xff"
"\xc0\xff\x00\xff"
"\xc0\x0a\xff\xff"
%%
int main(int argc, const char **argv)
{
    int i;

    for(i=1;i<argc;++i) {
        uint32_t addr = ntohl(strtoul(argv[i], 0, 16));
        if(in_word_set((char *)&addr, 4))
            printf("0x%08"PRIx32" is in the list.\n", htonl(addr));
        else
            printf("0x%08"PRIx32" is not in the list.\n", htonl(addr));
    }
    return 0;
}

另存为addrs.gperf,使用

进行编译和测试
gperf -l addrs.gperf > addrs.c
gcc addrs.c -o addrs
./addrs c0000000 c0010203 c0ffffff c00affff c0ff0aff c0ffff00 c0ff00ff