从字符串值派生的唯一数字ID

时间:2013-10-16 15:58:48

标签: java

如果我有一个由数字字母和连字符组成的唯一字符串ID,即

3c40df7f-1192-9fc9-ba43-5a2ffb833633

在Java中是否有任何方法可以生成这些ID的数字表示,并确保它们也是唯一的。

3 个答案:

答案 0 :(得分:2)

使用32位整数不能保证它们是唯一的。可能是BigInteger

public static void main(String Args[]) {
    String id = "3c40df7f-1192-9fc9-ba43-5a2ffb833633";
    BigInteger number = new BigInteger(id.replace("-", ""), Character.MAX_RADIX);
    System.out.println(number);
}

输出:

5870285826737482651911256837071133277773559673999

问题是以下结果是相同的:

3c40df7f-1192-9fc9-ba43-5a2ffb833633
3c40df7f1192-9fc9-ba43-5a2ffb83-3633

答案 1 :(得分:1)

您可以将字符串的字节直接滚动到BigInteger

public void test() {
  String id1 = "3c40df7f-1192-9fc9-ba43-5a2ffb833633";
  BigInteger b1 = new BigInteger(id1.getBytes());
  System.out.println("B1="+b1+ "("+b1.toString(16)+")");
  String id2 = "3c40df7f1192-9fc9-ba43-5a2ffb833633";
  BigInteger b2 = new BigInteger(id2.getBytes());
  System.out.println("B2="+b2+ "("+b2.toString(16)+")");
  String id3 = "Gruntbuggly I implore thee";
  BigInteger b3 = new BigInteger(id3.getBytes());
  System.out.println("B3="+b3+ "("+b3.toString(16)+")");
  // You can even recover the original.
  String s = new String(b3.toByteArray());
  System.out.println("s="+s);
}

打印

B1=99828927016901697435065009039863622178352177789384078556155000206819390954492243882803(33633430646637662d313139322d396663392d626134332d356132666662383333363333)
B2=389956746159772255607368246163988513318828061453840042257565172951767502233603027763(3363343064663766313139322d396663392d626134332d356132666662383333363333)
B3=114811070151326385608028676923400900586729364355854547418637669(4772756e74627567676c79204920696d706c6f72652074686565)
s=Gruntbuggly I implore thee

我想你现在需要通过Number来解释你的意思。

答案 2 :(得分:-1)

您可以将十六进制字符串转换为数字,如下所示:

String hexKey = "3c40df7f-1192-9fc9-ba43-5a2ffb833633";
long longKey = new BigInteger(hexKey.replace("-", ""), 16).longValue();

只要不带连字符的字符串是唯一的,生成的long也是唯一的。