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);
精彩评论