jweinst1
2/16/2018 - 6:19 PM

fast hashing algorithm

fast hashing algorithm

#include "stdio.h"

// djb2 hash example

unsigned long
hash(unsigned char *str)
{
    unsigned long hash = 5381;
    int c;

    while (c = *str++)
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */

    return hash;
}

int main(void) {
  printf("Hash of %s is %lu\n", "a", hash((unsigned char*)"a") % 2048);
  printf("Hash of %s is %lu\n", "b", hash((unsigned char*)"b") % 2048);
  printf("Hash of %s is %lu\n", "ab", hash((unsigned char*)"ab") % 2048);
  printf("Hash of %s is %lu\n", "foo", hash((unsigned char*)"foo") % 2048);
  printf("Hash of %s is %lu\n", "doo", hash((unsigned char*)"doo") % 2048);
  return 0;
}