Skip to content

Instantly share code, notes, and snippets.

@direvus direvus/hash.c
Created Oct 10, 2018

Embed
What would you like to do?
#include <stdio.h>
#include <string.h>
unsigned int hash(char *k) {
unsigned int result = 0;
size_t len = strlen(k);
if (len == 0) {
return 0;
} else if (len == 1) {
return k[0];
}
for (unsigned int i = 0; i < len - 1; i++) {
result <<= 1;
result += k[i+1] * (k[i] - 1);
}
return result;
}
int main(int argc, char **argv) {
if (argc < 2) {
const int SIZE = 1024;
char buf[SIZE];
while(fgets(buf, SIZE, stdin) != NULL) {
size_t pos = strlen(buf) - 1;
if (buf[pos] == '\n') {
buf[pos] = 0;
}
printf("%u\n", hash(buf));
}
return 0;
}
printf("%u\n", hash(argv[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.