Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert base-27 (or base-X) to base-10 in c#?

Tags:

c#

decimal

base

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 am not a very experienced programmer and would rather not do it from scratch if possible. Thanks!

like image 418
miltonjbradley Avatar asked Oct 09 '22 12:10

miltonjbradley


1 Answers

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.

like image 138
zmbq Avatar answered Oct 13 '22 08:10

zmbq