Get a unique integer value from a string

I have different unique lines in the same format. The line looks like axf25!j&809>-11~dc , and I want to get a unique integer value from this line. Each time this value should be the same and depends on the string. I tried converting each char string to int, and then I sum the characters to each other. But in case I have 2 lines with the same set of characters, they return integer values ​​equal to each other. So this does not suit me. How can I generate a unique integer value from a unique string?

UPDATE:

Having considered all the solutions provided, I decided to create a function that generates unique integer values. I hope this rules out collisions.

 public int getUniqueInteger(String name){ String plaintext = name; int hash = name.hashCode(); MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1,digest); String hashtext = bigInt.toString(10); // Now we need to zero pad it if you actually want the full 32 chars. while(hashtext.length() < 32 ){ hashtext = "0"+hashtext; } int temp = 0; for(int i =0; i<hashtext.length();i++){ char c = hashtext.charAt(i); temp+=(int)c; } return hash+temp; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } return hash; } 
+9
java string type-conversion integer
Jul 11 '13 at 1:22 on
source share
5 answers

You cannot generate a completely unique int from long enough strings because there are more 10-character strings than 32-bit integers .

As for non-unique solutions, you can use the standard hashCode function, its implementation in Java is quite good. For more complex things, you can consider a cryptographic hash ( SHA-2 , MD5 , etc.)

+8
Jul 11 '13 at 1:33
source share

You can simply use String.hashCode() (e.g. mystring.hashCode() ) to give you a certain degree of uniqueness, but you need to make sure that you can handle conflicts.

+7
Jul 11 '13 at 1:32
source share

You cannot guarantee unique integer values ​​from different strings, since there are more possible representations of strings than integers. You can use some known / specific hashing algorithm to minimize the chance of a collision. You should look at MD5 or SHA.

The java MessageDigest class should be useful.

+3
Jul 11 '13 at 1:31 on
source share

You can try with the code:

 import java.math.BigInteger; public static BigInteger stringToBigInteger(String text) { BigInteger bigInt = new BigInteger(text.getBytes()); return bigInt; } 

thank.

+1
Mar 15 '15 at 4:03
source share

Treat strings as a basic 0x110000 representation of an integer (you can leave with a smaller base if you know that the range of characters is limited). Convert to BigInteger .

0
Jul 11 '13 at 3:42 on
source share



All Articles