davivid
davivid

Reputation: 5960

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 string into a number to do this?

Upvotes: 2

Views: 3600

Answers (2)

Jorjon
Jorjon

Reputation: 5434

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.

Upvotes: 1

Mike
Mike

Reputation: 8545

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);

Upvotes: 1

Related Questions