c# Shorten int into case sensitive code

2019-05-06 23:36发布

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

4条回答
Bombasti
2楼-- · 2019-05-06 23:38

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));
查看更多
趁早两清
3楼-- · 2019-05-06 23:38

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"
查看更多
可以哭但决不认输i
4楼-- · 2019-05-06 23:44

Depending on your situation you might want to look at using Base32 as the restricted character set may be easier to read (I.E., some users cannot easily distinguish the difference between zero and the letter o).

You can find examples here and here.

查看更多
劳资没心,怎么记你
5楼-- · 2019-05-07 00:03
登录 后发表回答