Reputation: 10502
Is there a way to find the same integer/long or any digit number equivalent to a given string using java.
e.g If i give a string "Java_programming" it should give me always something like "7287272" digit.
The generated digit/number should be unique i.e. it should always generate "123" for "xyz" not "123" for "abc".
Upvotes: 0
Views: 2147
Reputation: 47392
First take your string and convert it to a sequence of bytes:
String a = "hello";
byte[] b = a.getBytes();
Now convert the bytes to a numeric representation, using BigInteger
BigInteger c = new BigInteger(b);
Finally, convert the BigInteger
back to a string using its toString()
method
String d = c.toString();
You are guaranteed to get the same output for the same input, and different outputs for different inputs. You can combine all of these into one step by doing
String d = new BigInteger(a.getBytes()).toString();
Upvotes: 0
Reputation: 93842
Call the hashCode method of your String
object.
I.e :
String t = "Java_programming";
String t2 = "Java_programming";
System.out.println(t.hashCode());
System.out.println(t2.hashCode());
Gives :
748582308
748582308
Using hashCode
in this case will meet your requirements (as you formuled it) but be careful, two different String
can produce the SAME hashCode
value ! (see @Dirk example)
Upvotes: 6
Reputation: 2563
It depends if you want that 2 different String have to give always 2 different identifiers.
String.hashCode()
can do what you want, the same string will give always the same ID but 2 different strings can also give the same ID.
If you want a unique identifier you can i.e. concatenate each byte character value from your string.
Upvotes: 0
Reputation: 16142
What are your requirements? You could just use a new BigInteger("somestring".toBytes("UTF-8")).toString()
to convert the string to a number, but will it do what you want?
Upvotes: 3
Reputation: 1806
Yes, it is possible. You can use String.hashCode() method on string. Here you find more details how integer returned by this method is created
Upvotes: 0
Reputation: 7844
Why don't you create a SHA-1 out of the string and use that as a key?
static HashFunction hashFunction = Hashing.sha1();
public static byte[] getHash(final String string) {
HashCode hashCode = hashFunction.newHasher().putBytes(string.getBytes).hash();
return hashCode.asBytes();
}
You can then do Bytes.toInt(hash)
or Bytes.toLong(hash)
Upvotes: 0