.NET 中的 base_convert

发布于 2024-07-16 07:40:30 字数 670 浏览 6 评论 0原文

.NET 是否具有与 PHP 的 base_convert 等效的本机函数,还是我需要编写自己的函数? 我想从任何基数转换为任何其他基数 - 其中“to”基数或“from”基数可以是 2-36 的任何整数。

PHP 函数的示例:base_convert($number_to_convert, $from_base, $to_base)

// convert 101 from binary to decimal
echo base_convert('101', 2, 10);
// 5

正如 Luke 在 Jon Skeet 的答案的评论中所指出的:Convert.ToString 无法处理与任何任意基数的转换,只能处理 2、8、10和 16

更新: 显然,答案是:不,没有本地方式。 下面,Erik 展示了一种实现此目的的方法。 另一个实现在这里: http://www.codeproject.com/KB/macros/Convert .aspx

Does .NET have a native function that is equivalent to PHP's base_convert or will I need to write my own? I want to convert from any base to any other base -- where either the 'to' base or the 'from' base can be any integer 2-36.

Example of the PHP function: base_convert($number_to_convert, $from_base, $to_base)

// convert 101 from binary to decimal
echo base_convert('101', 2, 10);
// 5

As noted by Luke in the comments of Jon Skeet's answer: Convert.ToString can't handle conversion to/from any arbitrary base, only 2, 8, 10 and 16

Update: Apparently, the answer is: no, there is no native way. Below, Erik shows one way to do this. Another implementation is here: http://www.codeproject.com/KB/macros/Convert.aspx

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

望喜 2024-07-23 07:40:30

编辑:这个答案非常方便,但仅适用于基数 2、8、10 和 16

您可以使用 Convert.ToInt32(text, base) 然后 Convert.ToString(number, base)

using System;

class Test
{
    static void Main()
    {
        int number = Convert.ToInt32("101", 2);
        string text = Convert.ToString(number, 10);
        Console.WriteLine(text); // Prints 5
    }
}

如果您要在基数 10 之间进行转换,则不需要需要指定 - 这是默认的。

请注意,这仅适用于基数 2、8、10 和 16。如果您想要其他内容,则必须编写自己的解析器/格式化程序。

EDIT: This answer is very convenient, but only works for bases 2, 8, 10 and 16

You can use Convert.ToInt32(text, base) and then Convert.ToString(number, base):

using System;

class Test
{
    static void Main()
    {
        int number = Convert.ToInt32("101", 2);
        string text = Convert.ToString(number, 10);
        Console.WriteLine(text); // Prints 5
    }
}

If you're converting to or from base 10, you don't need to specify that - it's the default.

Note that this only works for bases 2, 8, 10 and 16. If you want anything else, you'll have to write your own parser/formatter.

梦晓ヶ微光ヅ倾城 2024-07-23 07:40:30

下面是一些代码,可将整数转换为最多 36 的任意基数,并将基数 x 值的字符串表示形式转换为整数(给定基数):

class Program {
    static void Main(string[] args) {
        int b10 = 123;
        int targetBase = 5;

        string converted = ConvertToBase(b10, targetBase);
        int convertedBack = ConvertFromBase(converted, targetBase);

        string base3 = "212210";
        string base7 = ConvertFromBaseToBase(base3, 3, 7);

        Console.WriteLine(converted);
        Console.WriteLine(convertedBack);
        Console.WriteLine(base7);
        Console.ReadLine();
    }

    private const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static string ConvertToBase(int b10, int targetBase) {
        if (targetBase < 2) throw new ArgumentException("Target base must be greater than 2.", "targetBase");
        if (targetBase > 36) throw new ArgumentException("Target base must be less than 36.", "targetBase");

        if (targetBase == 10) return b10.ToString();

        StringBuilder result = new StringBuilder();

        while (b10 >= targetBase) {
            int mod = b10 % targetBase;
            result.Append(chars[mod]);
            b10 = b10 / targetBase;
        }

        result.Append(chars[b10]);

        return Reverse(result.ToString());
    }

    private static int ConvertFromBase(string bx, int fromBase) {
        if (fromBase < 2) throw new ArgumentException("Base must be greater than 2.", "fromBase");
        if (fromBase > 36) throw new ArgumentException("Base must be less than 36.", "fromBase");

        if (fromBase == 10) return int.Parse(bx);

        bx = Reverse(bx);
        int acc = 0;

        for (int i = 0; i < bx.Length; i++) {
            int charValue = chars.IndexOf(bx[i]);
            acc += (int)Math.Pow(fromBase, i) * charValue;
        }

        return acc;
    }

    public static string ConvertFromBaseToBase(string bx, int fromBase, int toBase) {
        int b10 = ConvertFromBase(bx, fromBase);
        return ConvertToBase(b10, toBase);
    }

    public static string Reverse(string s) {
        char[] charArray = new char[s.Length];
        int len = s.Length - 1;
        for (int i = 0; i <= len; i++)
            charArray[i] = s[len - i];
        return new string(charArray);
    }
}

如果您不关心显示这些值,则可以使用扩展字符集中的字符 - 如果您坚持使用普通的 ascii,理论上您可以拥有 base256 值。 除此之外,我建议不要使用字符,而是使用其他一些唯一可识别的值 - 尽管我不太看到这个值。

Here's some code that'll convert an integer to an arbitrary base up to 36, and convert a string representation of a base x value to an integer (given the base):

class Program {
    static void Main(string[] args) {
        int b10 = 123;
        int targetBase = 5;

        string converted = ConvertToBase(b10, targetBase);
        int convertedBack = ConvertFromBase(converted, targetBase);

        string base3 = "212210";
        string base7 = ConvertFromBaseToBase(base3, 3, 7);

        Console.WriteLine(converted);
        Console.WriteLine(convertedBack);
        Console.WriteLine(base7);
        Console.ReadLine();
    }

    private const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static string ConvertToBase(int b10, int targetBase) {
        if (targetBase < 2) throw new ArgumentException("Target base must be greater than 2.", "targetBase");
        if (targetBase > 36) throw new ArgumentException("Target base must be less than 36.", "targetBase");

        if (targetBase == 10) return b10.ToString();

        StringBuilder result = new StringBuilder();

        while (b10 >= targetBase) {
            int mod = b10 % targetBase;
            result.Append(chars[mod]);
            b10 = b10 / targetBase;
        }

        result.Append(chars[b10]);

        return Reverse(result.ToString());
    }

    private static int ConvertFromBase(string bx, int fromBase) {
        if (fromBase < 2) throw new ArgumentException("Base must be greater than 2.", "fromBase");
        if (fromBase > 36) throw new ArgumentException("Base must be less than 36.", "fromBase");

        if (fromBase == 10) return int.Parse(bx);

        bx = Reverse(bx);
        int acc = 0;

        for (int i = 0; i < bx.Length; i++) {
            int charValue = chars.IndexOf(bx[i]);
            acc += (int)Math.Pow(fromBase, i) * charValue;
        }

        return acc;
    }

    public static string ConvertFromBaseToBase(string bx, int fromBase, int toBase) {
        int b10 = ConvertFromBase(bx, fromBase);
        return ConvertToBase(b10, toBase);
    }

    public static string Reverse(string s) {
        char[] charArray = new char[s.Length];
        int len = s.Length - 1;
        for (int i = 0; i <= len; i++)
            charArray[i] = s[len - i];
        return new string(charArray);
    }
}

If you're unconcerned with displaying these values, you can use extended characters in your chars set - if you stick to plain ascii, you can theoretically have base256 values. Going beyond that I would recommend not using chars, but instead using some other uniquely-identifiable value - though I don't much see the value.

百思不得你姐 2024-07-23 07:40:30

在 ConvertToBase 中,以下行:

while (b10 > targetBase)

...应该是:

while (b10 >= targetBase)

它负责处理转换后的数字中弹出的基数(例如将“3”转换为基数 3)产生“3”而不是“10”)。

In ConvertToBase, the following line:

while (b10 > targetBase)

...should be:

while (b10 >= targetBase)

Which takes care of the base number popping up in the converted number (e.g. converting "3" into base 3 yields "3" instead of "10").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文