46 lines
1 KiB
C
46 lines
1 KiB
C
#include <stdint.h>
|
|
#include <stdio.h>
|
|
|
|
uint32_t murmur3_32(const uint8_t* key, size_t len, uint32_t seed) {
|
|
uint32_t h = seed;
|
|
uint32_t c1 = 0xcc9e2d51;
|
|
uint32_t c2 = 0x1b873593;
|
|
uint32_t k;
|
|
size_t i;
|
|
|
|
for (i = 0; i + 4 <= len; i += 4) {
|
|
k = *(uint32_t*)(key + i);
|
|
k *= c1;
|
|
k = (k << 15) | (k >> (32 - 15));
|
|
k *= c2;
|
|
|
|
h ^= k;
|
|
h = (h << 13) | (h >> (32 - 13));
|
|
h = h * 5 + 0xe6546b64;
|
|
}
|
|
|
|
// Tail handling
|
|
k = 0;
|
|
switch (len & 3) {
|
|
case 3: k ^= key[i + 2] << 16;
|
|
case 2: k ^= key[i + 1] << 8;
|
|
case 1: k ^= key[i + 0];
|
|
k *= c1; k = (k << 15) | (k >> (32 - 15)); k *= c2; h ^= k;
|
|
}
|
|
|
|
h ^= len;
|
|
h ^= h >> 16;
|
|
h *= 0x85ebca6b;
|
|
h ^= h >> 13;
|
|
h *= 0xc2b2ae35;
|
|
h ^= h >> 16;
|
|
|
|
return h;
|
|
}
|
|
|
|
int main() {
|
|
const char *key = "hello world";
|
|
uint32_t hash = murmur3_32((const uint8_t *)key, 11, 42); // seed = 42
|
|
printf("MurmurHash3 of \"%s\" is 0x%X\n", key, hash);
|
|
return 0;
|
|
}
|