Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Shorten int into case sensitive code

There are 26 characters in the alphabet (abc..yz) and 10 digits (0..9). That gives us a lexicon of 62 characters to use if we go case sensitive.

At the moment we are building a part of a filename based on an ID in our database. These numbers can get quite long so we would like to shorten them. For example instead of having:

file_459123.exe

We would rather:

file_aB5.exe

Does anyone have a method in C# that can convert an int into a shorter case sensitive string, and convert a case sensitive string back into an int?

Example (doesn't have to be this pattern):

1 = 1
2 = 2
...
9 = 9
10 = a
11 = b
...
36 = z
37 = A
like image 328
Tom Gullen Avatar asked Nov 28 '22 17:11

Tom Gullen


2 Answers

Despite the Base64 references, here's a generic (non-optimized) solution:

// for decimal to hexadecimal conversion use this:
//var digits = "0123456789abcdef".ToCharArray();

var digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
             .ToCharArray();

int number = 459123;
string output = "";

do
{
    var digit = digits[(int)(number%digits.Length)];
    output = output.Insert(0, digit.ToString());
    number = (int)number/digits.Length;
}
while (number > 0);

// output is now "1Vrd"
like image 119
M4N Avatar answered Dec 01 '22 07:12

M4N


just expanding M4Ns solution to a generic class....

  public class BaseX
    {
        private readonly string _digits;

        public BaseX(string digits)
        {
            _digits = digits;
        }
        public string ToBaseX(int number)
        {           
            var output = "";
            do
            {                
                output = _digits[number % _digits.Length] + output;
                number = number / _digits.Length;
            }
            while (number > 0);
            return output;
        }

        public int FromBaseX(string number)
        {
            return number.Aggregate(0, (a, c) => a*_digits.Length + _digits.IndexOf(c));
        }
    }

and then you can do...

var x = new BaseX("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
            Console.WriteLine(x.ToBaseX(10));
            Console.WriteLine(x.ToBaseX(459123));
            Console.WriteLine(x.ToBaseX(63));

            Console.WriteLine(x.FromBaseX("1Vrd"));
            Console.WriteLine(x.FromBaseX("A"));

            var bin = new BaseX("01");
            Console.WriteLine(bin.ToBaseX(10));
like image 29
Keith Nicholas Avatar answered Dec 01 '22 07:12

Keith Nicholas