UUID is a 128-bit value and in Java it is stored as two parts, the most significant bit (MSB) part which is the first 64 bits and the least significant bits (LSB) part which is the second half. These are stored as two long values in the UUID class. To compress the UUID we can use Base64 encoding. Here we will convert the UUID to bytes and then convert the bytes to Base64 encoded string. And for decompression, we convert the Base64 encoded string to bytes and then get the first 8 bytes using getLong()
which is the first 64 bit value, the MSB and then the next 8 bytes the LSB. UUID can be used for IDs in tables in DB and other places and instead of using the full representation, we can shorten it for efficient usage while preserving the uniqueness.
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.UUID;
public class UUIDUtils {
public static String compress(UUID uuid) {
ByteBuffer bf = ByteBuffer.wrap(new byte[16]);
bf.putLong(uuid.getMostSignificantBits());
bf.putLong(uuid.getLeastSignificantBits());
return Base64.getUrlEncoder().withoutPadding().encodeToString(bf.array());
}
public static String compress(String uuid) {
return compress(UUID.fromString(uuid));
}
public static UUID decompress(String b64String) {
byte[] bytes = Base64.getUrlDecoder().decode(b64String);
ByteBuffer bf = ByteBuffer.wrap(bytes);
long msb = bf.getLong();
long lsb = bf.getLong();
return new UUID(msb, lsb);
}
public static UUID genRandomUUID() {
return UUID.randomUUID();
}
}
We can try this interactively using JShell (Java Shell Tool).
jshell> /open UUIDUtils.java
jshell> System.out.println(UUIDUtils.genRandomUUID().toString());
b7321670-7ce0-4a3d-b939-b6f15213a48d
jshell> System.out.println(UUIDUtils.compress("b7321670-7ce0-4a3d-b939-b6f15213a48d"));
tzIWcHzgSj25ObbxUhOkjQ
jshell> System.out.println(UUIDUtils.decompress("tzIWcHzgSj25ObbxUhOkjQ"));
b7321670-7ce0-4a3d-b939-b6f15213a48d
Here we can see that the original UUID is 36 characters long and the shortened one is only 22 characters long.