1

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

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

Java中有什么方法可以生成这些ID的数字表示并确保它也是唯一的。

4

3 回答 3

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
于 2013-10-16T16:06:06.403 回答
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

于 2013-10-16T16:20:49.933 回答
-1

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

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

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

于 2013-10-16T16:05:54.393 回答