什么是转换到任意碱基C#功能的快速有效方法? [英] What's an Efficient Inversion of the Convert-to-Arbitrary-Base C# Function?

查看:118
本文介绍了什么是转换到任意碱基C#功能的快速有效方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个整数转换成一个base64字符重新presentation。我使用这个线程OxA3的回答是:<一href="http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net">http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net

I need to convert an integer into a base64-character representation. I'm using OxA3's answer on this thread: http://stackoverflow.com/questions/923771/quickest-way-to-convert-a-base-10-number-to-any-base-in-net

我如何逆这让我原来的整数回来,给定一个字符串?

How do I inverse this to get my original integer back, given a string?

推荐答案

<一个href="http://stackoverflow.com/questions/3579970/whats-an-efficient-inversion-of-the-convert-to-arbitrary-base-c-function/3580116#3580116">Joel穆勒的回答应该引导你的基部-64的情况下。

Joel Mueller's answer should guide you the base-64 case.

在回应你的<一个所提供的preliminary code href="http://stackoverflow.com/questions/3579970/whats-an-efficient-inversion-of-the-convert-to-arbitrary-base-c-function/3579977#3579977">your自己的答案,你绝对可以通过改变code提高其效率,以达到你的循环做(实际上是一个O(N)的IndexOf )使用哈希查找(这应该使O(1))。

In response to the preliminary code you've provided in your own answer, you can definitely improve its efficiency by changing the code to accomplish what your for loop is doing (effectively an O(N) IndexOf) to use a hash lookup (which should make it O(1)).

我的假设是 baseChars 是您在类的构造函数初始化一个领域立足​​这一点。如果这是正确的,做如下调整:

I am basing this on the assumption that baseChars is a field that you initialize in your class's constructor. If this is correct, make the following adjustment:

private Dictionary<char, int> baseChars;

// I don't know what your class is called.
public MultipleBaseNumberFormatter(IEnumerable<char> baseCharacters)
{
    // check for baseCharacters != null and Count > 0

    baseChars = baseCharacters
        .Select((c, i) => new { Value = c, Index = i })
        .ToDictionary(x => x.Value, x => x.Index);
}

然后在你的 StringToInt 方法:

char next = encodedString[currentChar];

// No enumerating -- we've gone from O(N) to O(1)!
if (!characterIndices.TryGetValue(next, out nextCharIndex))
{
    throw new ArgumentException("Input includes illegal characters.");
}

这篇关于什么是转换到任意碱基C#功能的快速有效方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆