我有相同格式的不同唯一字符串。该字符串看起来像这个axf25!j&809>-11~dc,我想从该字符串中获取唯一的整数值。 每次此值必须相同,并取决于字符串。 我试图将字符串的每个字符转换为int,然后将字符彼此求和。但是,如果我有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;
}

最佳答案

您不能从足够长的字符串because there are more 10-character strings than 32-bit integers生成完全唯一的int

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

10-04 21:55
查看更多