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

C# 十進位轉二進位、八進位、十六進位演算法實作

     編輯:關於C#

雖然 .NET 提供 Convert.ToString(value, base) 內建進制轉換,但理解手動演算法有助於掌握位元運算邏輯與面試準備。本文提供不使用內建函式的純演算法實作。

核心演算法:除基取餘法

通用步驟:

  1. 若數值 < 基數,直接回傳字串。
  2. 重複:餘數 = 數值 % 基數,數值 = 數值 / 基數,將餘數存入陣列。
  3. 直到數值 < 基數,最後數值為最高位。
  4. 反轉陣列順序並串接字串。

完整實作程式碼


using System;

public static class BaseConverter
{
    // 十進位轉二進位
    public static string ToBinary(int value)
    {
        if (value == 0) return "0";
        if (value < 0) throw new ArgumentException("僅支援非負整數");
        
        var bits = new System.Collections.Generic.List<char>();
        int n = value;
        while (n > 0)
        {
            bits.Add((char)('0' + (n & 1))); // 位元運算更高效
            n >>= 1;
        }
        bits.Reverse();
        return new string(bits.ToArray());
    }

    // 十進位轉八進位
    public static string ToOctal(int value)
    {
        if (value == 0) return "0";
        if (value < 0) throw new ArgumentException("僅支援非負整數");
        
        var digits = new System.Collections.Generic.List<char>();
        int n = value;
        while (n > 0)
        {
            digits.Add((char)('0' + (n % 8)));
            n /= 8;
        }
        digits.Reverse();
        return new string(digits.ToArray());
    }

    // 十進位轉十六進位
    public static string ToHexadecimal(int value)
    {
        if (value == 0) return "0";
        if (value < 0) throw new ArgumentException("僅支援非負整數");
        
        const string hexChars = "0123456789ABCDEF";
        var digits = new System.Collections.Generic.List<char>();
        int n = value;
        while (n > 0)
        {
            digits.Add(hexChars[n & 0xF]); // 取低 4 位
            n >>= 4;
        }
        digits.Reverse();
        return new string(digits.ToArray());
    }

    // 通用版本:支援任意基數 (2-36)
    public static string ToBase(int value, int baseNum)
    {
        if (baseNum < 2 || baseNum > 36)
            throw new ArgumentOutOfRangeException(nameof(baseNum), "基數必須在 2-36 之間");
        if (value == 0) return "0";
        if (value < 0) throw new ArgumentException("僅支援非負整數");
        
        const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var digits = new System.Collections.Generic.List<char>();
        int n = value;
        while (n > 0)
        {
            digits.Add(chars[n % baseNum]);
            n /= baseNum;
        }
        digits.Reverse();
        return new string(digits.ToArray());
    }
}

使用範例


Console.WriteLine(BaseConverter.ToBinary(42));        // 101010
Console.WriteLine(BaseConverter.ToOctal(42));         // 52
Console.WriteLine(BaseConverter.ToHexadecimal(42));   // 2A
Console.WriteLine(BaseConverter.ToBase(42, 3));       // 1120 (三進位)

內建方法對照


// .NET 內建方法(生產代碼建議使用)
Convert.ToString(42, 2);   // "101010"
Convert.ToString(42, 8);   // "52"
Convert.ToString(42, 16);  // "2A"
42.ToString("X");          // "2A" (十六進位大寫)
42.ToString("x");          // "2a" (十六進位小寫)

效能與擴充建議

  • 位元運算(&, >>)比除法/取餘快,適用於 2 的冪次基數(2、4、8、16、32)。
  • 支援負數:採用二補數表示或前綴負號。
  • 支援 long、BigInteger 大數值。
  • 格式化輸出:加入分隔符(如 0x、0b、每 4 位空格)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved