bkdrhash demo
bkdrhash demo
/* Start of bkdrhash.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <getopt.h> #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif /* End of defined(__cplusplus) || defined(c_plusplus) */ unsigned long BKDRHash(unsigned long seed, const char *str, unsigned int len) { if (str == NULL || seed == 0 || len == 0) { return 0; } static const int c1 = 0xcc9e2d51; static const int c2 = 0x1b873593; static const int r1 = 15; static const int r2 = 13; static const int m = 5; static const int n = 0xe6546b64; unsigned long hash = seed; const int nblocks = len / 4; const int *blocks = (const int *)str; int i; for (i = 0; i < nblocks; i++) { int k = blocks[i]; k *= c1; k = (k << r1) | (k >> (32 - r1)); k *= c2; hash ^= k; hash = ((hash << r2) | (hash >> (32 - r2))) * m + n; } const int *tail = (const int *)(str + nblocks * 4); int k1 = 0; switch (len & 3) { case 3: k1 ^= tail[2] << 16; case 2: k1 ^= tail[1] << 8; case 1: k1 ^= tail[0]; k1 *= c1; k1 = (k1 << r1) | (k1 >> (32 - r1)); k1 *= c2; hash ^= k1; } hash ^= len; hash ^= (hash >> 16); hash *= 0x85ebca6b; hash ^= (hash >> 13); hash *= 0xc2b2ae35; hash ^= (hash >> 16); return hash; } #if defined(__cplusplus) || defined(c_plusplus) } #endif /* End of defined(__cplusplus) || defined(c_plusplus) */ int main(int argc, char *argv[]) { if ( argc != 3 ) { fprintf(stderr, "Using: %s 1001 user111\n", argv[0]); return -1; } long seed = atol(argv[1]); const char *str = argv[2]; if (seed <= 0) { fprintf(stderr, "Error: %s\n", "seed must be greater than zero"); return -1; } if (str == NULL) { fprintf(stderr, "Error: %s\n", "string cannot be empty"); return -1; } fprintf(stdout, "Info: seed(%ld), str(%s)\n", seed, str); unsigned long result = BKDRHash((unsigned long)seed, str, strlen(str)); if ( result == 0 ) { fprintf(stderr, "Error: %s\n", "BKDRHash calculation failed"); return -1; } fprintf(stdout, "Info: BKDRHash result(%lu)\n", result); return 0; } /* End of bkdrhash.c */
====== End