简体   繁体   中英

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

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!

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.

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.

Assuming that you use base 26 using alphabet in one based (eg : A = 1, B = 2, ... , Z= 26, AA = 27, ... )

public int ToBase10(this string str)
{
    str = str.ToUpper();
    int number = 0;
    for (int index = 0; index < str.Length; index++)
        number += (str[index] - 'A' + 1) * (int)Math.Pow(26, str.Length - 1 - index);
    return number;
}

To call this function simply call like this

string PlateNumber = "TRX";
int number = PlateNumber.ToBase10();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM