Get unique integer value from string

integer, java, string, type-conversion

Solution

You cannot generate entirely unique `int`s from sufficiently long strings because there are more 10-character strings than 32-bit integers.

As far as non-unique solutions go, you can use the standard `hashCode` function, its implementation in Java is reasonably good. For more complex stuff you may consider computing cryptographic hash (SHA-2, MD5, etc.)

Problem

I have different unique strings in the same format. The string looks like this `axf25!j&809>-11~dc` and I want to get unique integer value from this string. Each time this value must be the same and depends on the string. I've tried to convert each char of the string to int and then I sum chars to each other. But in case if I have 2 strings with the same set of symbols, it return integer values which are equal to each other. So it doesn't suit me. How can I generate unique integer value from unique string? UPDATE: Having considered all given solutions I decided to create function which generate unique integer values. I hope that it excludes 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; } ```

Original source