开发者

as3 convert a string to an arbitrary number

I want to seed a number generator using a string input. What function would be best for simply turning the str开发者_StackOverflow社区ing into a number to do this?


The best approach is some simple algorithm of your creation, to avoid possible hacks. One method would be to add the value of each character using charCodeAt(),

function generateSeed(input:String):Number {
    var r:Number = 0;
    for (var i:int = 0; i < input.length; i++) {
        r += input.charCodeAt(i);
    }
    return r;
}

Also, depending on the required security, you can also try using MD5 or SHA-1.


If you're guaranteed that the input will be a number, you can simply cast it to a number from string through Number("4") ie.

var stringInput:String = "15"; // or wherever you're getting the input from
var seed:Number = Number(stringInput);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜