简体   繁体   English

Kotlin 将长字符串字母转换为数字 id

[英]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.我试图找到一种方法将像“T2hR8VAR4tNULoglmIbpAbyvdRi1y02rBX”这样的长字符串 ID 转换为数字 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我想过获取每个数字的 ASCII 值,然后将它们相加,但我认为这不是一个好方法,因为不同的数字可能具有相同的结果,例如,“ABC”和“BAC”将具有相同的结果结果

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

ABC = 10 + 20 + 50 = 80 ABC = 10 + 20 + 50 = 80

BAC = 20 + 10 + 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"我还想过获取每个字母的 ASCII 代码,然后将数字设置为彼此相邻,例如“ABC”

so ABC = 102050所以 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?这种方法不起作用,因为有一个 20 个字母的字符串会导致一个巨大的数字,那么我该如何解决这个问题呢? thank you in advance.先感谢您。

You can use the hashCode() function.您可以使用hashCode()函数。 "id".hashcode() . "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: hashCode的总合约为:

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.每当在同一个对象上多次调用它时, hashCode方法必须始终返回相同的整数,前提是对象上的equals比较中使用的信息没有被修改。

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.如果根据equals()方法两个对象相等,则对两个对象中的每一个调用hashCode方法必须产生相同的整数结果。

All platform object implements it by default.所有平台对象都默认实现它。 There is always a possibility for duplicates if you have lots of ids.如果您有很多 ID,则总是有可能出现重复项。

If you use a JVM based kotlin environment the hash will be produced by the String.hashCode() function from the JVM.如果您使用基于 JVM 的 kotlin 环境,则哈希将由 JVM 的String.hashCode()函数生成。

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.如果您需要 100% 确信没有可能的重复项,并且输入字符串最长可达 20 个字符,那么您不能将 ID 存储在 64 位 Long 中。 You will have to use BigInteger:您将不得不使用 BigInteger:

val id = BigInteger(stringId.toByteArray())

At that point, I question whether there is any point in converting the ID to a numerical format.那时,我质疑将 ID 转换为数字格式是否有任何意义。 The String itself can be the ID.字符串本身可以是 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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