2013-10-16 60 views
1

如果我有一个是由数字字母和连字符的唯一字符串ID,即唯一数字标识

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

有没有在Java中的任何方式来生成这些ID的数字表示和确保也是唯一的。

+2

[UUID与唯一整数ID?]可能重复(http://stackoverflow.com/questions/5563502/uuid-to-unique-integer-id) – Enrichman

+1

这样的字符串中的所有字母和数字都限制为十六进制数字,即'[0-9a-f]'? – rgettman

回答

-1

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

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

生成的长也是独一无二的,只要不带连字符字符串是独一无二的。

+0

实际上,只有字符串的最后16个字符(不包括连字符)才会考虑您的解决方案。由于OP给出的示例字符串长度为32个字符(加上一些连字符),我不认为这个解决方案适合OP。 –

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

则可以将字符串的字节数直接进入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的意思。

+0

当然,这是比我更好的解决方案。 –