22

我有相同格式的不同唯一字符串。字符串看起来像这样axf25!j&809>-11~dc,我想从这个字符串中获取唯一的整数值。每次这个值都必须相同并且取决于字符串。我试图将字符串的每个 char 转换为 int,然后将 char 相互相加。但是,如果我有 2 个具有相同符号集的字符串,它会返回彼此相等的整数值。所以不适合我。如何从唯一字符串生成唯一整数值​​?

更新:

考虑了所有给定的解决方案后,我决定创建生成唯一整数值​​的函数。我希望它排除碰撞。

public int getUniqueInteger(String name){
    String plaintext = name;
    int hash = name.hashCode();
    MessageDigest m;
    try {
        m = MessageDigest.getInstance("MD5");
        m.reset();
        m.update(plaintext.getBytes());
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1,digest);
        String hashtext = bigInt.toString(10);
        // Now we need to zero pad it if you actually want the full 32 chars.
        while(hashtext.length() < 32 ){
          hashtext = "0"+hashtext;
        }
        int temp = 0;
        for(int i =0; i<hashtext.length();i++){
            char c = hashtext.charAt(i);
            temp+=(int)c;
        }
        return hash+temp;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return hash;
}
4

5 回答 5

17

您可以只使用String.hashCode()(eg mystring.hashCode()) 来给您一定程度的独特性,但您必须确保您可以处理冲突。

于 2013-07-11T01:32:03.460 回答
15

您不能int从足够长的字符串生成完全唯一的 s,因为 10 字符的字符串比 32 位整数多

就非唯一解决方案而言,您可以使用标准hashCode函数,它在 Java 中的实现相当不错。对于更复杂的东西,您可以考虑计算加密哈希(SHA-2MD5等)

于 2013-07-11T01:33:52.387 回答
5

您不能保证来自不同字符串的唯一整数值​​,因为可能的字符串表示形式比整数多。您可以使用一些众所周知的/定义的散列算法来最大程度地减少冲突的机会。您应该查看 MD5 或 SHA。

java 类MessageDigest应该有一些用处。

于 2013-07-11T01:31:58.207 回答
2

您可以尝试使用代码:

import java.math.BigInteger;

public static BigInteger stringToBigInteger(String text) {
    BigInteger bigInt = new BigInteger(text.getBytes());
    return bigInt;
}

谢谢。

于 2015-03-15T04:03:33.630 回答
0

将字符串视为0x110000某个整数的基本表示形式(如果您知道字符范围有限,则可以使用较小的基数)。转换为BigInteger.

于 2013-07-11T03:42:09.623 回答