System.Convert 提供兩個核心方法支援 2/8/10/16 進制互轉:
Convert.ToInt32(string value, int fromBase):指定進制字串 → int (fromBase 僅限 2, 8, 10, 16)Convert.ToString(int value, int toBase):int → 指定進制字串 (toBase 僅限 2, 8, 10, 16)// 範例
int val = Convert.ToInt32("1010", 2); // 10
string bin = Convert.ToString(10, 2); // "1010"
string hex = Convert.ToString(255, 16); // "FF"
string oct = Convert.ToString(63, 8); // "77"
策略:來源進制字串 → 十進制整數 → 目標進制字串
public static string ConvertBase(string value, int fromBase, int toBase)
{
if (fromBase < 2 || fromBase > 36 || toBase < 2 || toBase > 36)
throw new ArgumentException("進制範圍需在 2-36 之間");
// 1. 來源進制字串轉十進制長整數 (支援大數值)
long decimalValue = 0;
foreach (char c in value.ToUpperInvariant())
{
int digit = c >= '0' && c <= '9' ? c - '0' : c - 'A' + 10;
if (digit >= fromBase) throw new FormatException($"字元 '{c}' 不屬於 {fromBase} 進制");
decimalValue = decimalValue * fromBase + digit;
}
// 2. 十進制轉目標進制字串
if (decimalValue == 0) return "0";
var digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = new System.Text.StringBuilder();
while (decimalValue > 0)
{
result.Insert(0, digits[(int)(decimalValue % toBase)]);
decimalValue /= toBase;
}
return result.ToString();
}
Console.WriteLine(ConvertBase("FF", 16, 2)); // 11111111
Console.WriteLine(ConvertBase("1111", 2, 16)); // F
Console.WriteLine(ConvertBase("Z", 36, 10)); // 35
Console.WriteLine(ConvertBase("100", 10, 36)); // 2S
Convert.ToInt32 僅支援 32 位有號整數範圍,大數值請用 Convert.ToInt64 或自訂 BigInteger 邏輯。