Самый быстрый способ преобразовать число с основанием 10 в любое основание в .NET?
I recently blogged about this. Моя реализация не использует dot-net никаких строковых операций visual-c# во время вычислений, что .cs-file делает ее очень быстрой. Поддерживается base преобразование в любую систему c#-language счисления с основанием от c# 2 до 36:
///
/// Converts the given decimal number to the numeral system with the
/// specified radix (in the range [2, 36]).
///
/// The number to convert.
/// The radix of the destination numeral system (in the range [2, 36]).
///
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;
}
Я также реализовал base быструю обратную функцию int на случай, если она кому-то c# понадобится: Arbitrary to Decimal Numeral System.
c#
.net
int
base
number-systems
Самый быстрый способ преобразовать число с основанием 10 в любое основание в .NET?
Мы используем файлы cookies для улучшения работы сайта. Оставаясь на нашем сайте, вы соглашаетесь с условиями использования файлов cookies. Чтобы ознакомиться с нашими Положениями о конфиденциальности и об использовании файлов cookie, нажмите здесь.