从字符串中获取唯一的整数值 [英] Get unique integer value from string

查看:465
本文介绍了从字符串中获取唯一的整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have different unique strings in the same format. The string looks like this axf25!j&809>-11~dc and I want to get unique integer value from this string. Each time this value must be the same and depends on the string. I've tried to convert each char of the string to int and then I sum chars to each other. But in case if I have 2 strings with the same set of symbols, it return integer values which are equal to each other. So it doesn't suit me. How can I generate unique integer value from unique string?

更新:

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

Having considered all given solutions I decided to create function which generate unique integer values. I hope that it excludes collisions.

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;
}


推荐答案

你无法生成完全独特的 int 来自足够长的字符串因为还有10个字符字符串而不是32位整数

You cannot generate entirely unique ints from sufficiently long strings because there are more 10-character strings than 32-bit integers.

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

As far as non-unique solutions go, you can use the standard hashCode function, its implementation in Java is reasonably good. For more complex stuff you may consider computing cryptographic hash (SHA-2, MD5, etc.)

这篇关于从字符串中获取唯一的整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆