Is there a way to find the same integer/long or any digit number equivalent to a given string using java.
eg If i give a string "Java_programming" it should give me always something like "7287272" digit.
The generated digit/number should be unique ie it should always generate "123" for "xyz" not "123" for "abc".
Call the hashCode method of your String
object.
Ie :
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)
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?
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)
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
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 ie concatenate each byte character value from your string.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.