Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a unique hash code for string input in android...?

I wanted to generate a unique hash code for a string in put in android. Is there any predefined library is there or we have to generate manually. Please any body if knows please present a link or a code stuff.

like image 316
Shashikant Avatar asked May 25 '11 06:05

Shashikant


People also ask

How do I create a hash code from a string?

Getting the hash code of a string is simple in C#. We use the GetHashCode() method. A hash code is a uniquely identified numerical value. Note that strings that have the same value have the same hash code.

Is hashCode of string unique?

They are not unique. Show activity on this post. By doing it's own hashing of the key String, that code risks the chance that two different key strings will generate the same integer map key and the code will fail in some situations. In general, the code should probably be using Map<String,String> .

How do I find the hashCode of a string?

Java - String hashCode() MethodUsing int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

Why does Java's hashCode () in string use 31 as a multiplier?

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional.


1 Answers

It depends on what you mean:

  • As mentioned String.hashCode() gives you a 32 bit hash code.

  • If you want (say) a 64-bit hashcode you can easily implement it yourself.

  • If you want a cryptographic hash of a String, the Java crypto libraries include implementations of MD5, SHA-1 and so on. You'll typically need to turn the String into a byte array, and then feed that to the hash generator / digest generator. For example, see @Bryan Kemp's answer.

  • If you want a guaranteed unique hash code, you are out of luck. Hashes and hash codes are non-unique.

A Java String of length N has 65536 ^ N possible states, and requires an integer with 16 * N bits to represent all possible values. If you write a hash function that produces integer with a smaller range (e.g. less than 16 * N bits), you will eventually find cases where more than one String hashes to the same integer; i.e. the hash codes cannot be unique. This is called the Pigeonhole Principle, and there is a straight forward mathematical proof. (You can't fight math and win!)

But if "probably unique" with a very small chance of non-uniqueness is acceptable, then crypto hashes are a good answer. The math will tell you how big (i.e. how many bits) the hash has to be to achieve a given (low enough) probability of non-uniqueness.

like image 115
Stephen C Avatar answered Sep 24 '22 16:09

Stephen C