C # Shorten int into case sensitive code

The alphabet (abc..yz) and 10 digits (0..9) have 26 characters. This gives us a lexicon of 62 characters to use if we are case sensitive.

We are currently creating a part of the file name based on the identifier in our database. These numbers can be quite long, so we would like to shorten them. For example, instead of:

file_459123.exe 

We would prefer:

 file_aB5.exe 

Does anyone have a method in C # that can convert an int to a shorter case-sensitive string and convert a case-sensitive string to int?

Example (does not have to be this template):

 1 = 1 2 = 2 ... 9 = 9 10 = a 11 = b ... 36 = z 37 = A 
+4
source share
4 answers

just extends the M4Ns solution to a universal 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)); 
+4
source

Despite Base64 links, there is a general (not optimized) solution here:

 // 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" 
+8
source

Try Base64

+6
source

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

Here you can find examples here .

+3
source

Source: https://habr.com/ru/post/1391318/


All Articles