Home > Uncategorized > Convert a number to a custom base in C# #Maths

Convert a number to a custom base in C# #Maths

b10

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;
}

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: