user86834
user86834

Reputation: 5645

Unique numeric IDs derived from string value

If I have an unique String IDs that is made up of numbers letters and hyphens, i.e.

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

is there any way in Java to generate a numeric representations of these IDs and ensure that will also be unique.

Upvotes: 1

Views: 778

Answers (3)

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

You can roll the bytes of the string directly into a 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);
}

prints

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

I suppose you now need to explain what you mean by Number.

Upvotes: 1

ovunccetin
ovunccetin

Reputation: 8663

You can convert a hexadecimal string to a number as follows:

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

The generated long is also unique as long as the string without hyphens is unique.

Upvotes: -1

Paul Vargas
Paul Vargas

Reputation: 42020

With 32-bit integers no guarantee that they are unique. Possibly with 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);
}

Output:

5870285826737482651911256837071133277773559673999

The problem is the result will be the same for the following:

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

Upvotes: 2

Related Questions