Java中的哈希代码生成器

时间:2011-11-15 10:54:42

标签: java algorithm

我正在寻找一个哈希码生成器,它将从这些字符生成一个唯一的哈希:[a-zA-Z0-9]并生成两个字符的哈希,如:aZ或{{1} }

不太可能发生碰撞;用Java。

3 个答案:

答案 0 :(得分:2)

散列的表示无关紧要。它是一个数字/字节数组,然后您可以将其转换为您喜欢的任何数字。 Base64,Hex等.Base64允许您使用ISO-8859-1中最少的字符数。另请注意,您不能只有两个ascii符号的良好哈希。它会导致碰撞。

答案 1 :(得分:2)

最简单的方法是乘以127(大于'Z'=> 122的最小素数)这对于长达4个字符的所有字符串都是唯一的,并且对于更长的字符串做一个不错的工作。即对于每个最多4个字符的字符串,您可以对字符串进行编码和解码并获取原始字符串。如果您需要更长的唯一ID,可以使用long,这样可以唯一地编码9个字符。


一个简单的解决方案

public static void main(String... args) {
    for (String s : "A,a,aa,AA,a1,A1,ABCD,1234,'hi bye'".split(",")) {
        long l = hashFor(s);
        String s2 = decode(l);
        System.out.printf("Hashcode for %s is %d, decoded is %s%n", s, l, s2);
    }
}

public static long hashFor(String s) {
    long l = 0;
    for (int i = 0; i < s.length(); i++)
        l = l * 127 + s.charAt(i);
    return l & Long.MAX_VALUE; // stay positive
}

public static String decode(long l) {
    StringBuilder sb = new StringBuilder(9);
    while (l > 0) {
        sb.append((char) (l % 127));
        l /= 127;
    }
    return sb.reverse().toString();
}

打印

Hashcode for A is 65, decoded is A
Hashcode for a is 97, decoded is a
Hashcode for aa is 12416, decoded is aa
Hashcode for AA is 8320, decoded is AA
Hashcode for a1 is 12368, decoded is a1
Hashcode for A1 is 8304, decoded is A1
Hashcode for ABCD is 134217986, decoded is ABCD
Hashcode for 1234 is 101183746, decoded is 1234
Hashcode for 'hi bye' is 21222006885704529, decoded is 'hi bye'

答案 2 :(得分:1)

你的[a-zA-Z0-9]是62个字符。因此,您的最终哈希值是一个2位数的基数62。计算普通的Java整数哈希值。用(62 ^ 2)修改它并将结果转换为基数62。