Is there a ready made function to be able to do base conversions in c#? I am looking to convert from base 26 and base base 27 numbers to base 10. I can do it on paper but i
Building off of your answer. You don't need a charset lookup list because you can just use the char ASCII Values.
int ConvertFromBase26(string number)
{
return number.Select(digit => (int)digit - 64).Aggregate(0, (x, y) => x * 26 + y);
}
I used this to convert column string addresses to int in while programming with Excel.
There is a ready-made function to convert numbers from base 2, 8 or 16 to base 10 ( Convert.ToInt32). If you want to convert numbers from base 26 or base 27 to base 10, you'll have to do it yourself.
Now, I've never heard of base 26 numbers, so I'm just going to assume the 'digits' are A to Z (A having a value of 0, and Z having a decimal value of 25). To convert from base 26 to base 10 you should do the following:
string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int GetDigitValue(char digit)
{
return charset.IndexOf(digit);
}
int ConvertFromBase26(string number)
{
int result = 0;
foreach(char digit in number)
result = result * charset.Length + GetDigitValue(digit);
return result;
}
To convert from base 27, just add whatever character represents 26.
Note: There's no error correction (you can convert the string "$#$@#$@" which will get you a nice negative number), and GetDigitValue is rather inefficient and should be replaced with a lookup table if you plan to do these conversions a lot.
EDIT: A LINQ version, just for kicks.
Again, no efficient lookup and no error correction, assuming the string consists only of legal digits.
string charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int ConvertFromBase(string charset, string number)
{
return number.Select(c=>charset.IndexOf(c)).Aggregate(0, (x, y) => x*charset.Length +y);
}
I think the first version is more readable, though.