Generate a unique identifier from an alphanumeric string

I need to create a UNIQUE id (only int) from an alphanumeric string.

eg. I have id = 'ABC123DEF' I must be able to generate a unique identifier (only int) for the "security identifier" so that the unique identifier is always constant.

eg. Security Identifier: ABC123DEF Int ID: 9463456892

So that I can store the Int ID in the database and at any time refer to the security identifier from the Int ID.

Some examples: PBG_CD_20120214_.2 | 201202-CMG188963_T | PBG_TD_20120306_.0001 3 examples: -PIPE seperated

+7
source share
2 answers

Just use the Java hashing algorithm. Not 100% unique, but you can use it as a base and add something to guarantee uniqueness on a much smaller set of collisions:

public static int hash(String s) { int h = 0; for (int i = 0; i < s.length(); i++) { h = 31 * h + s.charAt(i); } return h; } 

To avoid a 100% collision, you need a prime number that is larger than the wider difference between your characters. So, for 7-bit ASCII you need something above 128. So instead of 31, use 131 (the next prime number after 128). The part that I have not verified is that the generated hash will exceed the size of your long ints. But you can take it from there ...

+21
source

You can encode each character as a two-digit number, 0-9 as the numbers themselves, 10-35 as AZ.

For example, 9AC8 would be 09 10 12 08 = 09101208.

EDIT: For a small number, you can use this approach (using Java style psuedocode):

 char[] availableChars = ['A', 'B', ... , '0', ... '9', '-', '_', '.']; long hash = 0; long base = 1; for (char c in string.toCharArray()) for (int key=0; key < availableChars.length; key++) if (availableChars[key] != c) continue; hash += base*key; base = base*availableChars.length return hash; 
+1
source

All Articles