转化基地-27(或基本-X)立足-10在C#中? [英] Convert base-27 (or base-X) to base-10 in c#?

查看:118
本文介绍了转化基地-27(或基本-X)立足-10在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个现成的功能,能够做到基地的转换在C#?我期待从基地26和基地台27号基地10.我能做到这一点在纸上转换,但我不是一个非常有经验的程序员,如果可能的话宁可不从头开始做。谢谢!

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!

推荐答案

有一个现成的功能,人数从基地2个,8个或16转换为10进制(的 Convert.ToInt32 )。如果你想从数字基地26或基座27为10进制转换,你必须自己做。

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.

现在,我从来没有听说过基地26数字,所以我只是要承担的数字是A到Z(A,其值为0,并具有25十进制数值Z)。从基地26转换为10进制,你应该做到以下几点:

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

要从基地27转换,只需添加任何字符代表26。

To convert from base 27, just add whatever character represents 26.

注:没有纠错(你可以将字符串$#$ @#$ @,这将让你一个不错的负数),并且GetDigitValue是相当低效和应。可以用,如果你打算做这些转换大量的查找表替换

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.

编辑:LINQ的版本,只是踢

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.

这篇关于转化基地-27(或基本-X)立足-10在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆