For details about some common string hash Functions in C, refer.
The Code is as follows: |
Copy code |
// SDBM Hash Function Unsigned int SDBMHash (char * str) { Unsigned int hash = 0; While (* str) { // Equivalent to: hash = 65599 * hash + (* str ++ ); Hash = (* str ++) + (hash <6) + (hash <16)-hash; } Return (hash & 0x7FFFFFFF ); }
// RS Hash Function Unsigned int RSHash (char * str) { Unsigned int B = 378551; Unsigned int a = 63689; Unsigned int hash = 0; While (* str) { Hash = hash * a + (* str ++ ); A * = B; } Return (hash & 0x7FFFFFFF ); }
// JS Hash Function Unsigned int JSHash (char * str) { Unsigned int hash = 1315423911; While (* str) { Hash ^ = (hash <5) + (* str ++) + (hash> 2 )); } Return (hash & 0x7FFFFFFF ); }
// P. J. Weinberger Hash Function Unsigned int PJWHash (char * str) { Unsigned int BitsInUnignedInt = (unsigned int) (sizeof (unsigned int) * 8 ); Unsigned int ThreeQuarters = (unsigned int) (BitsInUnignedInt * 3)/4 ); Unsigned int OneEighth = (unsigned int) (BitsInUnignedInt/8 ); Unsigned int HighBits = (unsigned int) (0 xFFFFFFFF) <(BitsInUnignedInt-OneEighth ); Unsigned int hash = 0; Unsigned int test = 0; While (* str) { Hash = (hash <OneEighth) + (* str ++ ); If (test = hash & HighBits )! = 0) { Hash = (hash ^ (test> ThreeQuarters ))&(~ HighBits )); } } Return (hash & 0x7FFFFFFF ); }
// ELF Hash Function Unsigned int ELFHash (char * str) { Unsigned int hash = 0; Unsigned int x = 0; While (* str) { Hash = (hash <4) + (* str ++ ); If (x = hash & 0xF0000000L )! = 0) { Hash ^ = (x> 24 ); Hash & = ~ X; } } Return (hash & 0x7FFFFFFF ); }
// BKDR Hash Function Unsigned int BKDRHash (char * str) { Unsigned int seed = 131; // 31 131 1313 13131 131313 etc .. Unsigned int hash = 0; While (* str) { Hash = hash * seed + (* str ++ ); } Return (hash & 0x7FFFFFFF ); }
// DJB Hash Function Unsigned int DJBHash (char * str) { Unsigned int hash = 5381; While (* str) { Hash ++ (hash <5) + (* str ++ ); } Return (hash & 0x7FFFFFFF ); }
// AP Hash Function Unsigned int APHash (char * str) { Unsigned int hash = 0; Int I; For (I = 0; * str; I ++) { If (I & 1) = 0) { Hash ^ = (hash <7) ^ (* str ++) ^ (hash> 3 )); } Else { Hash ^ = (~ (Hash <11) ^ (* str ++) ^ (hash> 5 ))); } } Return (hash & 0x7FFFFFFF ); } |