Skip to content

Commit 5a6699f

Browse files
author
xtaci
committed
add a FNV string hash function
1 parent 09b836c commit 5a6699f

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

include/hash_string.h

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
* /--\ | (_| (_) | | |_ | | | | | _>
66
* _|
77
*
8-
* STRING HASH FUNCTION
8+
* STRING HASH FUNCTIONS
99
*
10-
* code taken from:
11-
* http://en.wikipedia.org/wiki/Java_hashCode()
10+
* 1. http://en.wikipedia.org/wiki/Java_hashCode()
11+
* 2. http://www.isthe.com/chongo/tech/comp/fnv/
1212
*
1313
******************************************************************************/
1414

@@ -33,6 +33,19 @@ namespace alg
3333

3434
return hash;
3535
}
36+
37+
static uint32_t hash_fnv1a(const char * str, uint32_t len)
38+
{
39+
uint32_t prime = 16777619U;
40+
uint32_t hash = 2166136261U;
41+
42+
for (int i=0;i<len;i++) {
43+
hash = hash ^ str[i];
44+
hash = hash * prime;
45+
}
46+
47+
return hash;
48+
}
3649
}
3750

3851
#endif //

src/hash_string_demo.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,25 @@ using namespace alg;
77
int main(void)
88
{
99
const char * strs[] = {
10+
"",
11+
"a",
12+
"foobar",
1013
"first string",
1114
"second string",
1215
"third string",
1316
"this is the fourth string",
1417
"and finally this is the fifth string"
1518
};
1619

20+
printf("using java hash\n");
1721
for (uint32_t i=0;i<sizeof(strs)/sizeof(char*);i++) {
18-
printf("hash string: %s --> %u\n", strs[i], hash_string(strs[i], strlen(strs[i])));
22+
printf("java hash: %s --> %x\n", strs[i], hash_string(strs[i], strlen(strs[i])));
1923
}
24+
25+
printf("using FNV hash\n");
26+
for (uint32_t i=0;i<sizeof(strs)/sizeof(char*);i++) {
27+
printf("fnv hash: %s --> %x\n", strs[i], hash_fnv1a(strs[i], strlen(strs[i])));
28+
}
29+
2030
return 0;
2131
}

0 commit comments

Comments
 (0)