c#任意进制转换

2020-10-10  本文已影响0人  AI视客

开发人员通常需要将十进制数转换为二进制、八进制、十六进制或其他进制。由于这是一个常见的任务,在互联网上有很多例子是如何做到的。你可以很容易地找到很多十进制到二进制,十进制到八进制,十进制到十六进制,等等,但是很难找到一个更通用的转换器,可以转换一个十进制数到任何其他进制。这就是我在这篇文章中要向你们展示的。该实现方法可以将任意十进制数转换为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

以下是该方法的实现:

/// <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;
}
上一篇下一篇

猜你喜欢

热点阅读