Question

I am making an application that involves a seed to generate a world and some games let you provide that seed with text. I'm wondering how would you 'convert' a string to an integer.

A simple way would be to use the ASCII values of all the characters and append them to a string which you would then parse to an integer, but that severely limits the size of the string. How would you be able to do this with a larger string?

EDIT: 64 bit not 32

Was it helpful?

Solution

I would just call String.hashcode(). The standard String.hashcode() function makes use of all characters in the target string and gives good dispersal.

The only thing I would question is whether 32 bits of seed is going to be enough. It might mean that your world generator could generate at most 232 different worlds.

OTHER TIPS

Random seeds for Random can be at least 48-bit, ideally 64-bit. You can write your own hash code like this.

public static long hashFor(String s) {
   long h = 0;
   for(int i = 0; i < s.length(); i++)
       h = h * 10191 + s.charAt(i);
   return h;
}

The Standard way for converting a String to Integer is using Integer.parseInt(String); You pass the string into this and it would convert the String to int. Try it and let me know!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top