从基座60转换为基体10 [英] convert from base 60 to base 10

查看:122
本文介绍了从基座60转换为基体10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个转换方法的 INT 来一个base60 字符串(使用0-9,az和AZ字符),但不能工作,如何回再次转换。下面是我的方法转换base10为base60:

I have a method that converts an int to a base60 string (using 0-9, a-z, and A-Z chars), but can't work out how to convert it back again. Here is my method for converting base10 to base60:

public static function toBase60(value:Number):String 
{
    var targetBase:uint = 60;
    value = value.toString().split('.')[0];
    var digits:Array = new Array();
    while (value > 0) 
    {
        digits.push(baseChars[value % targetBase]);
        value = Math.floor(value / targetBase);
    }
    var myResult:String = digits.reverse().join('');
    return myResult;
}

效果很好。但我怎么得到base60字符串返回到base10诠释?我碰巧使用ActionScript 3,但实际上,在任何编程语言的例子,一般的解释或sudo code将是巨大的。

Works well. But how do I get the base60 string back into a base10 int? I happen to be using ActionScript 3, but really, examples in any programming language, generic explanations or sudo code would be great.

推荐答案

这样做可能是一种方式:

One way of doing this could be:

    public static function fromBase60(value:String):Number {
        var result:Number = 0;
        var targetBase:uint = 60;
        var digitValue:int = 0;
        for(var i:int = 0, j:int = value.length - 1; j >= 0; i++,j--) {
            digitValue = reverseMap[value.charAt(j)];
            result += Math.pow(targetBase,i) * digitValue; 
        }
        return result;
    }

看起来你有一个数组,地图数字(数字)字符,所以你可以建立一个反向映射前期,使查找更容易。对于某些code是这样的:

Looks like you have an array that maps numbers (digits) to characters, so you could build a reverse map upfront and make the lookup easier. With some code like this:

    // add this code to your class
    private static var reverseMap:Object = {};

    private static function buildReverseMap():void {
        var len:int = baseChars.length;
        for(var i:int = 0; i < len; i++) {
            reverseMap[baseChars[i]] = i;
        }
    }

    // initialize the reverse map
    {
        buildReverseMap();
    }

修改

另一种实现的基础上,算法发布的汤姆Sirgedas。这避免了调用Math.pow,但我怀疑你会注意到在实际相差太大(性能明智):

Alternative implementation, based on algorithm posted by Tom Sirgedas. This avoids calling Math.pow, though I doubt you'll note much difference in practice (performance-wise):

    public static function fromBase60(value:String):Number {
        var result:Number = 0;
        var targetBase:uint = 60;
        var digitValue:int = 0;
        var len:int = value.length;
        for(var i:int = 0; i < len; i++) {
            digitValue = reverseMap[value.charAt(i)];
            result = result * targetBase + digitValue; 
        }
        return result;
    }

这篇关于从基座60转换为基体10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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