gpt4 book ai didi

c# - 将 10 进制数转换为 .NET 中任意进制数的最快方法?

转载 作者:IT王子 更新时间:2023-10-29 03:35:41 25 4
gpt4 key购买 nike

我有一个我写的旧的(大概)C# 方法,它接受一个数字并将其转换为任何基数:

string ConvertToBase(int number, char[] baseChars);

它并不是那么快速和整洁。在 .NET 中是否有一种好的、已知的方法来实现这一点?

我正在寻找允许我使用具有任意字符串的any base 的东西。

这只允许基数 16、10、8 和 2:

Convert.ToString(1, x);

我想利用它来利用数字、所有小写字母和所有大写字母来实现非常高的基数。喜欢this thread ,但对于 C# 而不是 JavaScript。

有人知道在 C# 中执行此操作的好方法吗?

最佳答案

Convert.ToString可用于将数字转换为指定基数中的等效字符串表示形式。

例子:

string binary = Convert.ToString(5, 2); // convert 5 to its binary representation
Console.WriteLine(binary); // prints 101

但是,正如评论所指出的,Convert.ToString 仅支持以下有限但通常足够的基数集:2、8、10 或 16。

更新(满足转换为任意基数的要求):

我不知道 BCL 中有任何方法能够将数字转换为任何基数,因此您必须编写自己的小实用程序函数。一个简单的示例看起来像这样(请注意,这肯定可以通过替换字符串连接来加快速度):

class Program
{
static void Main(string[] args)
{
// convert to binary
string binary = IntToString(42, new char[] { '0', '1' });

// convert to hexadecimal
string hex = IntToString(42,
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'});

// convert to hexavigesimal (base 26, A-Z)
string hexavigesimal = IntToString(42,
Enumerable.Range('A', 26).Select(x => (char)x).ToArray());

// convert to sexagesimal
string xx = IntToString(42,
new char[] { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x'});
}

public static string IntToString(int value, char[] baseChars)
{
string result = string.Empty;
int targetBase = baseChars.Length;

do
{
result = baseChars[value % targetBase] + result;
value = value / targetBase;
}
while (value > 0);

return result;
}

/// <summary>
/// An optimized method using an array as buffer instead of
/// string concatenation. This is faster for return values having
/// a length > 1.
/// </summary>
public static string IntToStringFast(int value, char[] baseChars)
{
// 32 is the worst cast buffer size for base 2 and int.MaxValue
int i = 32;
char[] buffer = new char[i];
int targetBase= baseChars.Length;

do
{
buffer[--i] = baseChars[value % targetBase];
value = value / targetBase;
}
while (value > 0);

char[] result = new char[32 - i];
Array.Copy(buffer, i, result, 0, 32 - i);

return new string(result);
}
}

更新 2(性能改进)

使用数组缓冲区而不是字符串连接来构建结果字符串可以提高性能,尤其是在处理大数字时(参见方法 IntToStringFast)。在最好的情况下(即最长可能的输入),此方法大约快三倍。但是,对于 1 位数字(即目标基数中的 1 位数字),IntToString 会更快。

关于c# - 将 10 进制数转换为 .NET 中任意进制数的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/923771/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com