雖然 .NET 提供 Convert.ToString(value, base) 內建進制轉換,但理解手動演算法有助於掌握位元運算邏輯與面試準備。本文提供不使用內建函式的純演算法實作。
通用步驟:
餘數 = 數值 % 基數,數值 = 數值 / 基數,將餘數存入陣列。
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 位空格)。