从字符串中获取唯一的整数值

时间:2013-07-11 01:22:55

标签: java string integer type-conversion

我有相同格式的不同唯一字符串。字符串看起来像这个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;
}

5 个答案:

答案 0 :(得分:12)

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

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

答案 1 :(得分:11)

您可以使用String.hashCode()(例如mystring.hashCode())为您提供一定程度的独特性,但您必须确保可以处理碰撞。

答案 2 :(得分:5)

您不能保证来自不同字符串的唯一整数值​​,因为有更多可能的字符串表示而不是整数。您可以使用一些众所周知/定义的散列算法来最小化碰撞的可能性。你应该看看MD5或SHA。

java类MessageDigest应该有用。

答案 3 :(得分:1)

您可以尝试使用代码:

import java.math.BigInteger;

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

感谢。

答案 4 :(得分:0)

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

相关问题