我知道这是单向函数,但我想将哈希码转换回有限的字符串集(使用 32 到 126 之间的字符)。有没有有效的方法来做到这一点?
最佳答案
这不仅可行,而且实际上非常简单,考虑到 String.hashCode
的定义。 。您可以创建一个带有任意起始点的“base 31”字符字符串,以将所有内容保持在正确的范围内,并根据该起始点减去偏移量。
这不一定是给定哈希码的最短字符串,但 7 个字符已经很短了:)
public class Test {
public static void main(String[] args) {
int hash = 100000;
String sample = getStringForHashCode(hash);
System.out.println(sample); // ASD^TYQ
System.out.println(sample.hashCode()); // 100000
}
private static final int OFFSET = "AAAAAAA".hashCode();
private static String getStringForHashCode(int hash) {
hash -= OFFSET;
// Treat it as an unsigned long, for simplicity.
// This avoids having to worry about negative numbers anywhere.
long longHash = (long) hash & 0xFFFFFFFFL;
System.out.println(longHash);
char[] c = new char[7];
for (int i = 0; i < 7; i++)
{
c[6 - i] = (char) ('A' + (longHash % 31));
longHash /= 31;
}
return new String(c);
}
}
关于java - 将哈希码转换为有限的字符串集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767035/