I need to generate a UNIQUE id (int only) from an Alphanumeric string.
e.g. I have security id = 'ABC123DEF' I should be able to generate an unique ID (int only) of "security id" so that the unique ID is always constant.
e.g. Security ID : ABC123DEF Int ID : 9463456892
So that I can store the Int ID in Database and refer the security ID from Int ID anytime.
Some Examples: PBG_CD_20120214_.2 | 201202-CMG188963_T | PBG_TD_20120306_.0001 3 examples :-PIPE seperated
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 collision set:
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;
}
In order to avoid collision 100%, you need a prime number that is bigger than the wider difference between your characters. So for 7-bit ASCII, you need something higher than 128. So instead of 31, use 131 (the next prime number after 128). The part I haven't checked is if the generated hash will wind up being bigger than the size of your long ints. But you can take it from there...
You could encode each character as a two-digit number, 0-9 as the numbers themselves, 10-35 as A-Z.
For example, 9AC8 would be 09 10 12 08 = 09101208.
EDIT: For a small number you could use this approach (with 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With