Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java UUID Compress & Decompress back

Tags:

java

uuid

I would like to do the following...

a) Compress a generated UUID to String of length 8.

b) Decompress the compressed UUID back to the original UUID.

The reason is because I have to send the UUID to a partnering system, and the partnering system only accepts 8 chars for UUID, and no I cannot request for a change to the partnering system.

So, what is left to do is to compress UUID that I have to 8 char string and then decompress it back to the original UUID when a message is gotten back from the partnering system.

Any ideas?

Thanks.

like image 245
rb8680 Avatar asked Aug 06 '12 02:08

rb8680


People also ask

Can you compress a UUID?

By virtue of being random enough to avoid collisions when generated in a distributed system, there is no way to compress UUID keys to the number of bits required to identify each record in the dataset.

How do I reduce my UUID size?

You can use base64 encoding and reduce it to 22 characters. If you use base94 you can get it does to 20 characters. If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes. If you don't care about Strings you can use 16, 8-bit bytes.

Is there a shorter version of UUID?

1. NanoID is Only 108 bytes in Size. Unlike UUID, NanoID is 4.5 times smaller in size and does not have any dependencies.


2 Answers

What you ask is impossible for information-theoretic reasons.

UUIDs as specified by RFC 4122 are 128 bits, as are UUID objects in Java.

Java Strings can store 16 bits per character, which would make for an 8-char string. However, not all bit sequences are valid UTF-16 strings, so in 8 characters you can store fewer than 128 bits of information.

So if you compress a UUID to a valid 8-character string, you have lost information, so in general there's no way to decompress it to retrieve the original UUID back.

What you might have intended is to generate a shorter string to use as a unique identifier. If so, see Generating 8-character only UUIDs.

like image 148
Mechanical snail Avatar answered Sep 22 '22 20:09

Mechanical snail


The best way to achieve url safe uuid compression is to encode it in base64

public class UUIDUtils {

  public static String compress(UUID uuid) {
    ByteBuffer bb = ByteBuffer.allocate(Long.BYTES * 2);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    byte[] array = bb.array();
    return Base64.getEncoder().encodeToString(array);
  }

  public static UUID decompress(String compressUUID) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.getDecoder().decode(compressUUID));
    return new UUID(byteBuffer.getLong(), byteBuffer.getLong());
  }


}

Result: 6227185c-b25b-4497-b821-ba4f8d1fb9a1 -> YicYXLJbRJe4IbpPjR+5oQ==

like image 25
xjodoin Avatar answered Sep 26 '22 20:09

xjodoin