Increment an index that uses numbers and characters (aka Base36 numbers)

后端 未结 4 795
感动是毒
感动是毒 2021-01-19 19:08

I have a string based code that can be either two or three characters in length and I am looking for some help in creating a function that will increment it.

Each \'

4条回答
  •  醉酒成梦
    2021-01-19 19:45

    Maintain the counter as an int and increment this. Convert the int to your character representation by modding and dividing by 36 iterativly. Map the modded range (0-35) to 0-Z.

    Example

    Updated with functions to go in either direction:

    internal class Program
    {
        const int Base = 36;
    
        public static void Main()
        {
            Console.WriteLine(ToInt("0AA"));
            Console.WriteLine(ToString(370));
        }
    
        private static string ToString(int counter)
        {
            List chars = new List();
    
            do
            {
                int c = (counter % Base);
    
                char ascii = (char)(c + (c < 10 ? 48 : 55));
    
                chars.Add(ascii);
            }
            while ((counter /= Base) != 0);
    
            chars.Reverse();
    
            string charCounter = new string(chars.ToArray()).PadLeft(3, '0');
    
            return charCounter;
        }
    
        private static int ToInt(string charCounter)
        {
            var chars = charCounter.ToCharArray();
    
            int counter = 0;
    
            for (int i = (chars.Length - 1), j = 0; i >= 0; i--, j++)
            {
                int chr = chars[i];
    
                int value = (chr - (chr > 57 ? 55 : 48)) * (int)Math.Pow(Base, j);
    
                counter += value;
            }
    
            return counter;
        }
    

    For more variants of conversion code see Quickest way to convert a base 10 number to any base in .NET?.

提交回复
热议问题