2

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

Ryxuma
  • 672
  • 5
  • 18

3 Answers3

6

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

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;
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
-1

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!

naushasame
  • 27
  • 3