几个HASH算法

/**  
* Hash算法大全<br>  
* 推荐使用FNV1算法  
* @algorithm None  
*
@author Goodzzp 2006-11-20  
* @lastEdit Goodzzp 2006-11-20   
* @editDetail Create  
*/  
public class HashAlgorithms   
{   
/**  
* 加法hash  
*
@param key 字符串  
*
@param prime 一个质数  
*
@return hash结果  
*/  
public static int additiveHash(String key, int prime)   
{   
  
int hash, i;   
  
for (hash = key.length(), i = 0; i < key.length(); i++)   
    hash
+= key.charAt(i);   
  
return (hash % prime);   
}   
  
/**  
* 旋转hash  
*
@param key 输入字符串  
*
@param prime 质数  
*
@return hash值  
*/  
public static int rotatingHash(String key, int prime)   
{   
  
int hash, i;   
  
for (hash=key.length(), i=0; i<key.length(); ++i)   
     hash
= (hash<<4)^(hash>>28)^key.charAt(i);   
  
return (hash % prime);   
//   return (hash ^ (hash>>10) ^ (hash>>20));   
}   
  
// 替代:   
// 使用:hash = (hash ^ (hash>>10) ^ (hash>>20)) & mask;   
// 替代:hash %= prime;   
  
  
/**  
* MASK值,随便找一个值,最好是质数  
*/  
static int M_MASK = 0x8765fed1;   
/**  
* 一次一个hash  
*
@param key 输入字符串  
*
@return 输出hash值  
*/  
public static int oneByOneHash(String key)   
{   
  
int   hash, i;   
  
for (hash=0, i=0; i<key.length(); ++i)   
   {   
     hash
+= key.charAt(i);   
     hash
+= (hash << 10);   
     hash
^= (hash >> 6);   
   }   
   hash
+= (hash << 3);   
   hash
^= (hash >> 11);   
   hash
+= (hash << 15);   
//   return (hash & M_MASK);   
   return hash;   
}   
  
/**  
* Bernstein's hash  
*
@param key 输入字节数组  
*
@param level 初始hash常量  
*
@return 结果hash  
*/  
public static int bernstein(String key)   
{   
  
int hash = 0;   
  
int i;   
  
for (i=0; i<key.length(); ++i) hash = 33*hash + key.charAt(i);   
  
return hash;   
}   
  
//   
////
Pearson's Hash   
// char pearson(char[]key, ub4 len, char tab[256])   
// {   
//   char hash;   
//   ub4 i;   
//   for (hash=len, i=0; i<len; ++i)    
//     hash=tab[hash^key[i]];   
//   return (hash);   
// }   
  
//// CRC Hashing,计算crc,具体代码见其他   
// ub4 crc(char *key, ub4 len, ub4 mask, ub4 tab[256])   
// {   
//   ub4 hash, i;   
//   for (hash=len, i=0; i<len; ++i)   
//     hash = (hash >> 8) ^ tab[(hash & 0xff) ^ key[i]];   
//   return (hash & mask);   
// }   
  
/**  
* Universal Hashing  
*/  
public static int universal(char[]key, int mask, int[] tab)   
{   
  
int hash = key.length, i, len = key.length;   
  
for (i=0; i<(len<<3); i+=8)   
   {   
    
char k = key[i>>3];   
    
if ((k&0x01) == 0) hash ^= tab[i+0];   
    
if ((k&0x02) == 0) hash ^= tab[i+1];   
    
if ((k&0x04) == 0) hash ^= tab[i+2];   
    
if ((k&0x08) == 0) hash ^= tab[i+3];   
    
if ((k&0x10) == 0) hash ^= tab[i+4];   
    
if ((k&0x20) == 0) hash ^= tab[i+5];   
    
if ((k&0x40) == 0) hash ^= tab[i+6];   
    
if ((k&0x80) == 0) hash ^= tab[i+7];   
   }   
  
return (hash & mask);   
}   
  
/**  
* Zobrist Hashing  
*/    
public static int zobrist( char[] key,int mask, int[][] tab)   
{   
  
int hash, i;   
  
for (hash=key.length, i=0; i<key.length; ++i)   
     hash
^= tab[i][key[i]];   
  
return (hash & mask);   
}   
  
// LOOKUP3    
// 见Bob Jenkins(3).c文件   
  
// 32位FNV算法   
static int M_SHIFT = 0;   
/**  
* 32位的FNV算法  
*
@param data 数组  
*
@return int值  
*/  
   
public static int FNVHash(byte[] data)   
    {   
       
int hash = (int)2166136261L;   
       
for(byte b : data)   
            hash
= (hash * 16777619) ^ b;   
       
if (M_SHIFT == 0)   
           
return hash;   
       
return (hash ^ (hash >> M_SHIFT)) & M_MASK;   
    }   
   
/**  
     * 改进的32位FNV算法1  
     *
@param data 数组  
     *
@return int值  
    
*/  
   
public static int FNVHash1(byte[] data)   
    {   
       
final int p = 16777619;   
       
int hash = (int)2166136261L;   
       
for(byte b:data)   
            hash
= (hash ^ b) * p;   
        hash
+= hash << 13;   
        hash
^= hash >> 7;   
        hash
+= hash << 3;   
        hash
^= hash >> 17;   
        hash
+= hash << 5;   
       
return hash;   
    }   
   
/**  
     * 改进的32位FNV算法1  
     *
@param data 字符串  
     *
@return int值  
    
*/  
   
public static int FNVHash1(String data)   
    {   
       
final int p = 16777619;   
       
int hash = (int)2166136261L;   
       
for(int i=0;i<data.length();i++)   
            hash
= (hash ^ data.charAt(i)) * p;   
        hash
+= hash << 13;   
        hash
^= hash >> 7;   
        hash
+= hash << 3;   
        hash
^= hash >> 17;   
        hash
+= hash << 5;   
       
return hash;   
    }   
  
   
/**  
     * Thomas Wang的算法,整数hash  
    
*/    
   
public static int intHash(int key)   
    {   
      key
+= ~(key << 15);   
      key
^= (key >>> 10);   
      key
+= (key << 3);   
      key
^= (key >>> 6);   
      key
+= ~(key << 11);   
      key
^= (key >>> 16);   
     
return key;   
    }   
   
/**  
     * RS算法hash  
     *
@param str 字符串  
    
*/  
   
public static int RSHash(String str)   
    {   
       
int b    = 378551;   
       
int a    = 63689;   
       
int hash = 0;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= hash * a + str.charAt(i);   
          a   
= a * b;   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of RS Hash Function */  
  
   
/**  
     * JS算法  
    
*/  
   
public static int JSHash(String str)   
    {   
      
int hash = 1315423911;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
^= ((hash << 5) + str.charAt(i) + (hash >> 2));   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of JS Hash Function */  
  
   
/**  
     * PJW算法  
    
*/  
   
public static int PJWHash(String str)   
    {   
       
int BitsInUnsignedInt = 32;   
       
int ThreeQuarters     = (BitsInUnsignedInt * 3) / 4;   
       
int OneEighth         = BitsInUnsignedInt / 8;   
       
int HighBits          = 0xFFFFFFFF << (BitsInUnsignedInt - OneEighth);   
       
int hash              = 0;   
       
int test              = 0;   
  
      
for(int i = 0; i < str.length();i++)   
       {   
          hash
= (hash << OneEighth) + str.charAt(i);   
  
         
if((test = hash & HighBits) != 0)   
          {   
             hash
= (( hash ^ (test >> ThreeQuarters)) & (~HighBits));   
          }   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of P. J. Weinberger Hash Function */  
  
   
/**  
     * ELF算法  
    
*/  
   
public static int ELFHash(String str)   
    {   
       
int hash = 0;   
       
int x    = 0;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= (hash << 4) + str.charAt(i);   
         
if((x = (int)(hash & 0xF0000000L)) != 0)   
          {   
             hash
^= (x >> 24);   
             hash
&= ~x;   
          }   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of ELF Hash Function */  
  
   
/**  
     * BKDR算法  
    
*/  
   
public static int BKDRHash(String str)   
    {   
       
int seed = 131; // 31 131 1313 13131 131313 etc..   
        int hash = 0;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= (hash * seed) + str.charAt(i);   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of BKDR Hash Function */  
  
   
/**  
     * SDBM算法  
    
*/  
   
public static int SDBMHash(String str)   
    {   
       
int hash = 0;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= str.charAt(i) + (hash << 6) + (hash << 16) - hash;   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of SDBM Hash Function */  
  
   
/**  
     * DJB算法  
    
*/  
   
public static int DJBHash(String str)   
    {   
      
int hash = 5381;   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= ((hash << 5) + hash) + str.charAt(i);   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   
   
/* End Of DJB Hash Function */  
  
   
/**  
     * DEK算法  
    
*/  
   
public static int DEKHash(String str)   
    {   
       
int hash = str.length();   
  
      
for(int i = 0; i < str.length(); i++)   
       {   
          hash
= ((hash << 5) ^ (hash >> 27)) ^ str.charAt(i);   
       }   
  
      
return (hash & 0x7FFFFFFF);   
    }   

<think>好的,我现在需要回答用户关于常见哈希算法示例代码的问题。首先,我得确认用户的需求是什么。他们提到想查找常见的哈希算法示例,特别是示例代码。根据用户提供的引用,特别是引用[1]、[2]、[3],里面提到了Java和C++中的哈希算法实现,以及不同方法如直接定址法、除留余数法等。 首先,我应该列举几种常见的哈希算法,并给出每种算法的简单说明和代码示例。需要确保代码使用正确的格式,比如Python的话用代码块,但用户提供的引用中有Java和C++的例子,但用户可能希望示例代码用哪种语言呢?引用[3]中有C++的示例,而用户的问题中没有明确指定语言,可能需要用常见的语言,比如Python或Java。不过原引用中的示例是C++,可能需要调整。或者可能用户希望看到不同语言的示例? 另外,用户的问题中提到“常见hash算法示例代码”,而引用中提到的哈希算法包括Object的hashCode、直接定址法、数学分析、平方取中等。需要将这些方法转化为代码示例。 我需要确保每个算法都给出名称、说明、示例代码,并正确引用提供的资料。例如,引用[3]中的C++代码示例有直接定址法、除留余数法等,可能需要转换为Python或其他语言的示例,但用户可能希望保持原语言?或者用户希望看到多种语言的示例? 另外,用户提供的引用[1]提到Java中的hashCode(),引用[3]有C++的不同哈希方法。可能需要分点说明不同的哈希算法,并给出对应的代码示例。例如,直接定址法、除留余数法、平方取中法、折叠法、MD5、SHA系列等。 但需要注意的是,像MD5和SHA属于加密哈希函数,而直接定址法等是哈希表的构造方法。用户可能指的是哈希表中的哈希函数,还是包括加密哈希算法?根据引用[3]中的内容,可能更多是哈希表的构造方法,如直接定址、平方取中等。 因此,我需要将常见的哈希函数构造方法列出,并给出代码示例。例如: 1. 直接定址法:H(key) = a*key + b 2. 除留余数法:H(key) = key mod p 3. 平方取中法:取key平方的中间几位 4. 折叠法:将key分成几部分相加 5. 乘法哈希法:用key乘以一个常数后取小数部分再乘以表大小 然后,每个方法给出示例代码,比如用Python或Java实现。例如,直接定址法可以用简单的线性函数,除留余数法使用模运算,平方取中法需要将数字平方后取中间位数。 同时,根据引用[3]中的C++示例,可能需要参考这些方法的实现,并将其转换为其他语言的代码。例如,直接定址法的C++代码是: int hash(int key) { return (3 * key + 5); // a=3, b=5 } 对应的Python代码可以是: def direct_address_hash(key): return 3 * key + 5 对于除留余数法,C++示例是: int hash(int key) { return key % 1009; // p=1009 } Python实现类似: def division_hash(key, p=1009): return key % p 平方取中法需要处理数字的平方后的中间部分。例如,C++代码: int hash(int key) { long square = key * key; square = square / 100; // 去掉后两位 return square % 1000; // 取中间三位 } 转换为Python: def square_mid_hash(key): square = key ** 2 square = square // 100 # 去掉最后两位 return square % 1000 # 取中间三位 折叠法的话,例如将数字分成每部分三位数相加: def folding_hash(key): key_str = str(key) parts = [int(key_str[i:i+3]) for i in range(0, len(key_str), 3)] return sum(parts) % 1000 # 假设表大小为1000 此外,可能还需要提到常见的加密哈希函数如MD5、SHA-1、SHA-256,虽然这些通常由库提供,但可以展示如何使用Python的hashlib库生成它们的哈希值。 例如: import hashlib def md5_hash(data): return hashlib.md5(data.encode()).hexdigest() def sha256_hash(data): return hashlib.sha256(data.encode()).hexdigest() 不过用户的问题可能更关注于哈希表的哈希函数,而不是加密哈希。需要根据引用内容判断,引用[3]中的示例都是哈希表的构造方法,因此可能应重点放在这些上。 总结,我需要分点列出常见的哈希算法(构造方法),给出说明和代码示例,并正确引用提供的参考资料。例如,引用[3]中的直接定址法、除留余数法等,以及引用[1]中的Java hashCode()。 可能的结构: 常见哈希算法示例代码: 1. 直接定址法 - 说明:H(key)=a*key + b - 代码示例(Python): def direct_hash(key): return 3 * key + 5 2. 除留余数法 - 说明:H(key) = key % p,p通常为质数 - 代码示例: def division_hash(key, p=1009): return key % p 3. 平方取中法 - 说明:平方后取中间几位 - 代码示例: def square_mid_hash(key): square = key ** 2 square = square // 100 return square % 1000 4. 折叠法 - 说明:分割相加 - 代码示例: def folding_hash(key): parts = [int(str(key)[i:i+3]) for i in range(0, len(str(key)), 3)] return sum(parts) % 1000 5. 乘法哈希法 - 说明:使用黄金分割比例 - 代码示例: def multiplication_hash(key, size): A = (math.sqrt(5) - 1) / 2 return int(size * ((key * A) % 1)) 此外,还可以提到Java中的hashCode()实现,如引用[1]中的Object#hashCode(),但具体实现可能因对象而异,例如String的哈希计算。 最后,需要生成相关问题,例如不同哈希算法的适用场景,如何解决冲突,如何选择哈希函数等,根据引用[2]和[3]中的内容。</think>### 常见哈希算法示例代码 以下是几种常见哈希算法的实现示例,涵盖基础哈希函数构造方法和实际应用: --- #### 1. **直接定址法** **说明**:哈希函数为线性表达式 $H(key) = a \cdot key + b$,适合键值分布均匀的场景[^3]。 ```python def direct_address_hash(key: int) -> int: a = 3 b = 5 return a * key + b ``` --- #### 2. **除留余数法** **说明**:哈希函数为 $H(key) = key \mod p$,其中 $p$ 通常选择接近哈希表大小的质数以减少冲突。 ```python def division_hash(key: int, table_size: int) -> int: p = 1009 # 示例质数 return key % p ``` --- #### 3. **平方取中法** **说明**:将键值平方后取中间几位作为哈希值,适合键值范围不确定的场景。 ```python def square_mid_hash(key: int) -> int: square = key ** 2 square = square // 100 # 去掉最后两位 return square % 1000 # 取中间三位 ``` --- #### 4. **折叠法** **说明**:将键值分割为多部分并求和,再取模得到哈希值,适合长键值(如字符串)。 ```python def folding_hash(key: str) -> int: key_str = str(key) parts = [int(key_str[i:i+3]) for i in range(0, len(key_str), 3)] return sum(parts) % 1000 # 假设表大小为1000 ``` --- #### 5. **乘法哈希法** **说明**:利用黄金分割比例计算 $H(key) = \lfloor size \cdot (key \cdot A \mod 1) \rfloor$,分布均匀性较好。 ```python import math def multiplication_hash(key: int, table_size: int) -> int: A = (math.sqrt(5) - 1) / 2 # 黄金分割比例 fractional_part = (key * A) % 1 return int(table_size * fractional_part) ``` --- #### 6. **加密哈希算法(MD5)** **说明**:生成固定长度的哈希值,常用于数据完整性验证[^1]。 ```python import hashlib def md5_hash(data: str) -> str: return hashlib.md5(data.encode()).hexdigest() ``` --- #### 7. **Java 的 `hashCode()`** **说明**:Java 对象的默认哈希实现,例如 `String` 的哈希计算为加权和: ```java // Java 示例 public int hashCode() { int hash = 0; for (int i = 0; i < length(); i++) { hash = 31 * hash + charAt(i); } return hash; } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值