Convert a number to a custom base in C# #Maths
We naturally count in base 10 (decimal), and if you do some programming, then you’ll be familiar with base 2 (binary), and base 16 (hex).
So, what about if you wanted to make your own custom base, like base 36 or base 25?, here’s some code to covert a custom base (base36) to decimal and back again
private static int ConvertToBaseAlpha(string alpha)
{
string strBase = “ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”;
int intValue = 0;
int intPower = 1;
foreach(char c in Enumerable.Reverse(alpha.ToCharArray()))
{
var intPosValue = strBase.IndexOf(c);
intValue += intPosValue * intPower;
intPower *= strBase.Length;
}
return intValue;
}private static string ConvertFromBaseAlpha(double alpha)
{
string strBase = “ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890”;
string strValue = “”;
int intPower = strBase.Length;
while((int)alpha!=0)
{
var intMod = (int)(alpha % intPower);
alpha /= intPower;
strValue = strBase.Substring(intMod, 1) + strValue;
}
return strValue;
}
Thanks for the code. The strBase is wrong. It should be 0-9 and A-Z. Also don’t forget to convert string alpha to upper case first before converting.
LikeLike