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 \'
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?.