本文最后更新于:June 30, 2023 pm

一个非常简单的HASH函数

// 参考:https://zhuanlan.zhihu.com/p/54017133
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define NEW_LONG() (unsigned long *)malloc(sizeof(unsigned long))

//ASCII HASH 函数:把字符串的ASCII码的二进制拿出来拼一个整数
unsigned long ASCII_HASH(int size, char str[], int len)
{
    unsigned long *v = NEW_LONG();
    // 内存转换,实际上是吧字符串的值直接给干到long那边去
    // 假设字符串是 "012" 则对应的内存为:48,49,50,转到long那边去
    // 其实就是:48 49 50 00 。。。。
    // 如果字符串是确定的,则long一定是唯一的一个数
    // 不好的一点是,当字符串的值多于32个(unsigned long)的时候就会溢出,增加碰撞的几率
    memcpy(v, str, len);
    unsigned long hash_value = ((*v) % size);
    printf("[LOG] HASH('%s') ==> %lu, at entry[%lu]\n", str, *v, hash_value);
    return hash_value;
}
int main(int argc, char const *argv[])
{
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "a1", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "b2", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "c3", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "d4", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "e5", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "f6", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "g7", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "h8", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "i9", 2));
    printf("Test === Hash:%lu\n", ASCII_HASH(10, "j0", 2));
    return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!

一个非常简单的解释器 Previous
Shell编程之-常见性能指标获取 Next