c#任意進制轉(zhuǎn)換

開發(fā)人員通常需要將十進制數(shù)轉(zhuǎn)換為二進制、八進制、十六進制或其他進制。由于這是一個常見的任務,在互聯(lián)網(wǎng)上有很多例子是如何做到的。你可以很容易地找到很多十進制到二進制,十進制到八進制,十進制到十六進制,等等,但是很難找到一個更通用的轉(zhuǎn)換器,可以轉(zhuǎn)換一個十進制數(shù)到任何其他進制。這就是我在這篇文章中要向你們展示的。該實現(xiàn)方法可以將任意十進制數(shù)轉(zhuǎn)換為2到36進制的任意進制。

long number = 123456789;
Console.WriteLine("Decimal: " + number.ToString());
Console.WriteLine("Binary : " + DecimalToArbitrarySystem(number,  2));
Console.WriteLine("Octal  : " + DecimalToArbitrarySystem(number,  8));
Console.WriteLine("Hex    : " + DecimalToArbitrarySystem(number, 16));
Console.WriteLine("Base 36: " + DecimalToArbitrarySystem(number, 36));

// This example displays the following output:
// Decimal: 123456789
// Binary : 111010110111100110100010101
// Octal  : 726746425
// Hex    : 75BCD15
// Base 36: 21I3V9

以下是該方法的實現(xiàn):

/// <summary>
/// Converts the given decimal number to the numeral system with the
/// specified radix (in the range [2, 36]).
/// </summary>
/// <param name="decimalNumber">The number to convert.</param>
/// <param name="radix">The radix of the destination numeral system
/// (in the range [2, 36]).</param>
/// <returns></returns>
public static string DecimalToArbitrarySystem(long decimalNumber, int radix)
{
    const int BitsInLong = 64;
    const string Digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    if (radix < 2 || radix > Digits.Length)
        throw new ArgumentException("The radix must be >= 2 and <= " +
            Digits.Length.ToString());

    if (decimalNumber == 0)
        return "0";

    int index = BitsInLong - 1;
    long currentNumber = Math.Abs(decimalNumber);
    char[] charArray = new char[BitsInLong];

    while (currentNumber != 0)
    {
        int remainder = (int)(currentNumber % radix);
        charArray[index--] = Digits[remainder];
        currentNumber = currentNumber / radix;
    }

    string result = new String(charArray, index + 1, BitsInLong - index - 1);
    if (decimalNumber < 0)
    {
        result = "-" + result;
    }

    return result;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容