Reputation: 443
I know it's one-way function but I want to convert hashcode back to limited set of string (using char between 32 to 126). Is there an efficient way to do this?
Upvotes: 2
Views: 4445
Reputation: 533790
Actually, I only need one string from that hashcode. I want to make Minecraft seed shortener.
The simplest way to turn an int
value into a short string is to use
String s = Integer.toString(n, 36); // uses base 36.
Upvotes: 0
Reputation: 1503140
It's not only feasible - it's actually pretty simple, given the definition for String.hashCode
. You can just create a string of "base 31" characters with some arbitrary starting point to keep everything in the right range, subtracting an offset based on that starting point.
This isn't necessarily the shortest string with the given hash code, but 7 characters is pretty short :)
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);
}
}
Upvotes: 4