Java recreate string from hashcode

前端 未结 5 1644
眼角桃花
眼角桃花 2020-12-10 15:45

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.         


        
相关标签:
5条回答
  • 2020-12-10 16:22

    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).

    0 讨论(0)
  • 2020-12-10 16:23

    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.

    0 讨论(0)
  • 2020-12-10 16:27

    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.

    0 讨论(0)
  • 2020-12-10 16:33

    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.

    0 讨论(0)
  • 2020-12-10 16:41

    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à.

    0 讨论(0)
提交回复
热议问题