下面是一些代码,可以将整数转换为最多 36 的任意基数,并将基数 x 值的字符串表示形式转换为整数(给定基数):
class Program {
static void Main(string[] args) {
int b10 = 123;
int targetBase = 5;
string converted = ConvertToBase(b10, targetBase);
int convertedBack = ConvertFromBase(converted, targetBase);
string base3 = "212210";
string base7 = ConvertFromBaseToBase(base3, 3, 7);
Console.WriteLine(converted);
Console.WriteLine(convertedBack);
Console.WriteLine(base7);
Console.ReadLine();
}
private const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string ConvertToBase(int b10, int targetBase) {
if (targetBase < 2) throw new ArgumentException("Target base must be greater than 2.", "targetBase");
if (targetBase > 36) throw new ArgumentException("Target base must be less than 36.", "targetBase");
if (targetBase == 10) return b10.ToString();
StringBuilder result = new StringBuilder();
while (b10 >= targetBase) {
int mod = b10 % targetBase;
result.Append(chars[mod]);
b10 = b10 / targetBase;
}
result.Append(chars[b10]);
return Reverse(result.ToString());
}
private static int ConvertFromBase(string bx, int fromBase) {
if (fromBase < 2) throw new ArgumentException("Base must be greater than 2.", "fromBase");
if (fromBase > 36) throw new ArgumentException("Base must be less than 36.", "fromBase");
if (fromBase == 10) return int.Parse(bx);
bx = Reverse(bx);
int acc = 0;
for (int i = 0; i < bx.Length; i++) {
int charValue = chars.IndexOf(bx[i]);
acc += (int)Math.Pow(fromBase, i) * charValue;
}
return acc;
}
public static string ConvertFromBaseToBase(string bx, int fromBase, int toBase) {
int b10 = ConvertFromBase(bx, fromBase);
return ConvertToBase(b10, toBase);
}
public static string Reverse(string s) {
char[] charArray = new char[s.Length];
int len = s.Length - 1;
for (int i = 0; i <= len; i++)
charArray[i] = s[len - i];
return new string(charArray);
}
}
如果你不关心显示这些值,你可以在你的字符集中使用扩展字符——如果你坚持纯 ascii,理论上你可以有 base256 值。除此之外,我建议不要使用字符,而是使用其他一些唯一可识别的值——尽管我看不到它的价值。