Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortening java UUID while preserving the uniqueness

Tags:

java

uuid

base62

I'm trying to make the java UUID shorter while preserving the same uniqueness as the UUID has. I wrote the following code:

public static void main(String[] args) {
    UUID uid=UUID.randomUUID();
    String shortId=to62System(uid.getMostSignificantBits())+
        to62System(uid.getLeastSignificantBits());

    System.out.println(shortId);
}

static char[] DIGITS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static int RADIX = DIGITS.length;

public static String to62System(long value) {
    if (value == 0) {
        return "0";
    } else {
        char[] buf = new char[11];
        int charPos = 10;
        long i = value;
        while (i != 0) {
            buf[charPos--] = DIGITS[Math.abs((int) (i % RADIX))];
            i /= RADIX;
        }
        return new String(buf, charPos + 1, (10 - charPos));
    }
}

Am I doing it right or did I overlooked something important?

like image 649
Fipil Avatar asked Dec 03 '13 20:12

Fipil


1 Answers

I use org.apache.commons.codec.binary.Base64 to convert a UUID into a url-safe unique string that is 22 characters in length and has the same uniqueness as UUID.

I posted my code on Storing UUID as base64 String

like image 113
stikkos Avatar answered Sep 28 '22 19:09

stikkos