-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_function.c
93 lines (82 loc) · 1.39 KB
/
hash_function.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include "hash_function.h"
// treat strings as base-256 integers
// with digits in the range 1 to 255
// for m that is large prime
unsigned long
modhash(const char *s, unsigned long m)
{
unsigned long h;
unsigned const char *us;
// ensure elements are treated as having values >= 0
us = (unsigned const char *)s;
h = 0;
while (*us != '\0')
{
h = (h * BASE + *us) % m;
us++;
}
return (h);
}
// multiplier can be any small prime number
unsigned long
mulhash(const char *s)
{
unsigned long h;
unsigned const char *us;
us = (unsigned const char *)s;
h = 0;
while (*us != '\0')
{
h = h * MULTIPLIER + *us;
us++;
}
return h;
}
// bits per char depends on machine
unsigned long
xorhash(const char *s, unsigned long x[])
{
unsigned long h;
unsigned const char *us;
int i;
unsigned char c;
int shift;
us = (unsigned const char *)s;
h = 0;
for (i = 0; *us != '\0' && i < MAX_BITS; us++)
{
c = *us;
for (shift = 0; shift < BITS_PER_CHARl shift++, i++)
{
// is low bit of c set?
if (c & 0x1)
h ^= x[i];
// shift c to get new bit in lowest position
c >>= 1;
}
}
return (h);
}
unsigned long
sdbm(const char *s)
{
unsigned long h;
h = 0;
while (*s != '\0')
{
h = *s + (h << 6) + (h << 16) - h;
s++;
}
return (h);
}
unsigned long djb2(const char *s)
{
unsigned long h;
h = 5381;
while (*s != '\0')
{
h = ((h < 5) + h) + *s;
s++;
}
return (h);
}