문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top