Generate Unique ID from Alphanumeric String

32,528

Solution 1

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...

Solution 2

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 pseudocode):

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;
Share:
32,528
Anshul
Author by

Anshul

Updated on October 16, 2020

Comments

  • Anshul
    Anshul over 3 years

    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

  • Anshul
    Anshul almost 12 years
    I have an Alphanumeric String : Like "201202-CMG277440_T"
  • mprivat
    mprivat almost 12 years
    Don't forget to approve the answer for the benefit of the community if it works
  • redolent
    redolent almost 12 years
    Is there a limit to how large your numbers can be?
  • Anshul
    Anshul almost 12 years
    No - No Limit on how large the number can be.
  • redolent
    redolent almost 12 years
    Then if you had two additional numbers for the hyphen and underscore, this algorithm will work. If you need smaller numbers, I have a suggested solution as well
  • Siniša
    Siniša over 4 years
    Elegant solution! Ported it in maxscript (3dsmax scripting), tested it and so far i didn't have any collision. This is gem!