Advertisement
CuriousStudent

MurmurHash2

Dec 6th, 2021
357
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1.  
  2. unsigned int Bloom::MurmurHash2(const void* key, int len, unsigned int seed)
  3. {
  4.     // 'm' and 'r' are mixing constants generated offline.
  5.     // They're not really 'magic', they just happen to work well.
  6.     const unsigned int m = 0x5bd1e995;
  7.     const int r = 24;
  8.  
  9.     // Initialize the hash to a 'random' value
  10.  
  11.     unsigned int h = seed ^ len;
  12.  
  13.     // Mix 4 bytes at a time into the hash
  14.  
  15.     const unsigned char* data = (const unsigned char*)key;
  16.  
  17.     while (len >= 4)
  18.     {
  19.         unsigned int k = *(unsigned int*)data;
  20.  
  21.         k *= m;
  22.         k ^= k >> r;
  23.         k *= m;
  24.  
  25.         h *= m;
  26.         h ^= k;
  27.  
  28.         data += 4;
  29.         len -= 4;
  30.     }
  31.  
  32.     // Handle the last few bytes of the input array
  33.  
  34.     switch (len)
  35.     {
  36.     case 3: h ^= data[2] << 16;
  37.     case 2: h ^= data[1] << 8;
  38.     case 1: h ^= data[0];
  39.         h *= m;
  40.     };
  41.  
  42.     // Do a few final mixes of the hash to ensure the last few
  43.     // bytes are well-incorporated.
  44.  
  45.     h ^= h >> 13;
  46.     h *= m;
  47.     h ^= h >> 15;
  48.  
  49.     return h % data_bit_size;
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement