1

I need to generate unique strings starting from int number (id). The length must be proportionally incremental, so for tiny ids I have to generate unique strings of four characters. For big ids I have to generate strings much more complex, with growing size when needed (max 8 digit) in order to accomplish the uniqueness. All this procedure must be done with two opposite functions:

from id -> obtain string

from string -> obtain id

Unique strings must be composed by numbers and characters of a specific set (379CDEFHKJLMNPQRTUWXY)

Is there a well know algorithm to do this? I need to do this in c# or better in tsql. Ideas are also appreciated.

Edit

I have "simply" the need to encode (and than decode) the number. I've implemented this routines for my alphabet (21 symbols length): Encode:

public static String BfEncode(long input)
{
    if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
    char[] clistarr = BfCharList.ToCharArray();
    var result = new Stack<char>();
    while (input != 0)
    {
        result.Push(clistarr[input % 21]);
        input /= 21;
    }
    return new string(result.ToArray());
} 

And decode:

public static Int64 BfDecode(string input)
{
    var reversed = input.ToLower().Reverse();
    long result = 0;
    int pos = 0;
    foreach (char c in reversed)
    {
        result += BfCharList.IndexOf(c.ToString().ToUpper()) * (long)Math.Pow(21, pos);
        pos++;
    }
    return result;
}

I've generated example strings in a loop starting from 10000 to 10000000 (!). Starting from 10K I can generate strings of 4 digits length. After the generation I've put all the strings in a list and checked for uniqueness (I've done it with parallel foreach...). At the number 122291 the routine thrown an exception because there is a duplicate! Is it possibile? The base conversion to a custom alphabet is not a good solution?

G10
  • 555
  • 1
  • 5
  • 15
  • Does it matter if the process of int -> str can be reversed by the string's consumer? If not just base36 encode, if it does: [Integer ID obfuscation techniques](http://stackoverflow.com/questions/2565478/integer-id-obfuscation-techniques). – Alex K. Mar 13 '14 at 15:00
  • 1
    Are you trying to encrypt, or just encode? How many characters do you want for a 1-digit id? For a 2-digit id? For an 8-digit id? There are many ways to encode an integer, but you have to be very specific in defining your requirements. – Jim Mischel Mar 13 '14 at 15:00
  • Well, It's basically just converting the number to another base. Take a look at the accepted answer [here](http://stackoverflow.com/questions/9559122/convert-base-27-or-base-x-to-base-10-in-c) – Ebbe M. Pedersen Mar 13 '14 at 19:09

0 Answers0