简体   繁体   中英

Kotlin Convert long String letters to a numerical id

I'm trying to find a way to convert a long string ID like "T2hR8VAR4tNULoglmIbpAbyvdRi1y02rBX" to a numerical id.

I thought about getting the ASCII value of each number and then adding them up but I don't think that this is a good way as different numbers can have the same result, for example, "ABC" and "BAC" will have the same result

A = 10, B = 20, C = 50,

ABC = 10 + 20 + 50 = 80

BAC = 20 + 10 + 50 = 80

I also thought about getting each letters ASCII code, then set the numbers next to each other for example "ABC"

so ABC = 102050

this method won't work as having a 20 letter String will result in a huge number, so how can I solve this problem? thank you in advance.

You can use the hashCode() function. "id".hashcode() . All objects implement a variance of this function.

From the documentation :

open fun hashCode(): Int

Returns a hash code value for the object. The general contract of hashCode is:

Whenever it is invoked on the same object more than once, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.

If two objects are equal according to the equals() method, then calling the hashCode method on each of the two objects must produce the same integer result.

All platform object implements it by default. There is always a possibility for duplicates if you have lots of ids.

If you use a JVM based kotlin environment the hash will be produced by the String.hashCode() function from the JVM.

If you need to be 100% confident that there are no possible duplicates, and the input Strings can be up to 20 characters long, then you cannot store the IDs in a 64-bit Long. You will have to use BigInteger:

val id = BigInteger(stringId.toByteArray())

At that point, I question whether there is any point in converting the ID to a numerical format. The String itself can be the ID.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM