Richard J. Ross III
Richard J. Ross III

Reputation: 55583

Java recreate string from hashcode

Is there any way that I can use a hashcode of a string in java, and recreate that string?

e.g. something like this:

String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
    System.out.println("Hmm, something went wrong: " + myNewstring);

I say this, because I must turn a string into an integer value, and reconstruct that string from that integer value.

Upvotes: 9

Views: 29600

Answers (6)

user14831455
user14831455

Reputation:

You could do something like this:

char[] chars = "String here".toCharArray();
int[] ints = new int[chars.length];
for (int i = 0; i < chars.length; i++) {
    ints[i] = (int)chars[i];
}

Then:

char[] chars = new char[ints.length]
for (int i = 0; i < chars.length; i++) {
    chars[i] = (char)ints[i];
}
String final = new String(chars);

I have not actually tested this yet... It is just "concept" code.

Upvotes: 0

hyperneutrino
hyperneutrino

Reputation: 5425

For example, "1019744689" and "123926772" both have a hashcode of -1727003481. This proves that for any integer, you might get a different result (i.e. reversehashcode(hashcode(string)) != string).

Upvotes: 1

Cephalopod
Cephalopod

Reputation: 15145

Let's assume the string consists only of letters, digits and punctuation, so there are about 70 possible characters.

log_70{2^32} = 5.22...

This means for any given integer you will find a 5- or 6-character string with this as its hash code. So, retrieving "Hello World": impossible; but "Hello" might work if you're lucky.

Upvotes: 0

Andrew
Andrew

Reputation: 1023

Impossible I'm afraid. Think about it, a hashcode is a long value i.e. 8 bytes. A string maybe less than this but also could be much longer, you cannot squeeze a longer string into 8 bytes without losing something.

The Java hashcode algorithm sums every 8th byte if I remember correctly so you'd lose 7 out of 8 bytes. If your strings are all very short then you could encode them as an int or a long without losing anything.

Upvotes: 2

JustinKSU
JustinKSU

Reputation: 4999

No. Multiple Strings can have the same hash code. In theory you could create all the Strings that have have that hash code, but it would be near infinite.

Upvotes: 4

Ted Hopp
Ted Hopp

Reputation: 234857

This is impossible. The hash code for String is lossy; many String values will result in the same hash code. An integer has 32 bit positions and each position has two values. There's no way to map even just the 32-character strings (for instance) (each character having lots of possibilities) into 32 bits without collisions. They just won't fit.

If you want to use arbitrary precision arithmetic (say, BigInteger), then you can just take each character as an integer and concatenate them all together. Voilà.

Upvotes: 6

Related Questions