Skip to content

Instantly share code, notes, and snippets.

@igorwwwwwwwwwwwwwwwwwwww
Created December 8, 2016 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igorwwwwwwwwwwwwwwwwwwww/4fb1a4587ef1713b289271e644339266 to your computer and use it in GitHub Desktop.
Save igorwwwwwwwwwwwwwwwwwwww/4fb1a4587ef1713b289271e644339266 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
/* Generic hash function (a popular one from Bernstein).
* I tested a few and this was the best. */
uint32_t dictGenHashFunction(const uint8_t *buf, int len) {
uint32_t hash = 5381;
while (len--)
hash = ((hash << 5) + hash) + (*buf++); /* hash * 33 + c */
return hash;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: djb <str>...");
return 1;
}
for (int i = 1; i < argc; i++) {
uint8_t *arg = malloc(strlen(argv[i]) * sizeof(uint8_t));
strncpy((uint8_t *)arg, argv[i], strlen(argv[i])+1);
printf("%u %s\n", dictGenHashFunction(arg, strlen(arg)), arg);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment