Convert an arbitrary string to float in range 0 and 1
I'd like to convert an arbitrary string (or for easier process a string hash) to a float number between 0 and 1. The purpose is to create a function that returns a color code for a given string so the user always sees that entity in the same color that is generated from its name.
OP included this code in comments (included here for readability):
var hashed:String = MD5.hash(input); // creates a 32 long hexa
const max:Number = Number("0xffffffffffffffffffffffffffffffff");
var hashedHexa:Number开发者_如何学JAVA = Number("0x" + hashed);
return hashedHexa/max;
Since you're asking us to create an algorithm; there are many ways to do so. I might try something with the charCodeAt method. Conceptually something like this:
public function stringToDecimal(value:String):Number{
var results : Number = 0;
// loop over each character in string
for(var index:int = 0;index< value.length; index++){
// this code turns each character in the string to a number and adds them all together
// divide by 100 b/c we know all ASCII charcodes will be between 0 & 127. This will give
// a decimal result
results += (value.charCodeAt(index)/100);
}
return results
}
This algorithm will not guarantee that every string will return a unique number; but that wasn't one of your requirements.
精彩评论