首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 進制轉換實作:Convert 類別與自訂通用方法

     編輯:關於C#

.NET 內建 Convert 方法

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 邏輯。
  • 進制字母不分大小寫,建議統一轉大寫處理。
  • 自訂方法支援 2-36 進制 (0-9, A-Z),超出範圍需擴充字元集。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved