Created
February 4, 2014 13:57
-
-
Save dzeban/8803995 to your computer and use it in GitHub Desktop.
Jenkins hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* jhash.c - Simple Jenkins hash. | |
* | |
* Copyright (C) 2006. Bob Jenkins (bob_jenkins@burtleburtle.net) | |
* http://burtleburtle.net/bob/hash/ | |
* | |
* Sources taken from Linux kernel implementation. | |
* Copyright (C) 2009-2010 Jozsef Kadlecsik (kadlec@blackhole.kfki.hu) | |
* | |
* Turned into userspace program by avd | |
* Copyright (C) 2014 Alex Dzyoba <avd@reduct.ru> | |
* | |
* This code as original Bob's code is in public domain. | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
/* An arbitrary initial parameter */ | |
#define JHASH_INITVAL 0xdeadbeef | |
typedef unsigned int u32; | |
#define rol32(a,s) a << s | |
/* __jhash_final - final mixing of 3 32-bit values (a,b,c) into c */ | |
#define __jhash_final(a, b, c) \ | |
{ \ | |
c ^= b; c -= rol32(b, 14); \ | |
a ^= c; a -= rol32(c, 11); \ | |
b ^= a; b -= rol32(a, 25); \ | |
c ^= b; c -= rol32(b, 16); \ | |
a ^= c; a -= rol32(c, 4); \ | |
b ^= a; b -= rol32(a, 14); \ | |
c ^= b; c -= rol32(b, 24); \ | |
} | |
/* jhash_3words - hash exactly 3, 2 or 1 word(s) */ | |
static inline u32 jhash_3words(u32 a, u32 b, u32 c, u32 initval) | |
{ | |
a += JHASH_INITVAL; | |
b += JHASH_INITVAL; | |
c += initval; | |
__jhash_final(a, b, c); | |
return c; | |
} | |
static inline u32 jhash_2words(u32 a, u32 b, u32 initval) | |
{ | |
return jhash_3words(a, b, 0, initval); | |
} | |
static inline u32 jhash_1word(u32 a, u32 initval) | |
{ | |
return jhash_3words(a, 0, 0, initval); | |
} | |
void usage() | |
{ | |
fprintf(stderr, "Usage: ./jhash <integer to hash>\n"); | |
fprintf(stderr, "Input integer must fit in 4 bytes (u32).\n"); | |
} | |
int main(int argc, const char *argv[]) | |
{ | |
u32 hash; | |
u32 val; | |
char *errptr = NULL; | |
if(argc != 2) | |
{ | |
usage(); | |
return EXIT_FAILURE; | |
} | |
val = strtol(argv[1], &errptr, 10); | |
if( *errptr != 0 || errno == ERANGE ) | |
{ | |
usage(); | |
return EXIT_FAILURE; | |
} | |
hash = jhash_1word(val, 0x16278182); | |
printf("%08x\n", hash); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment