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.
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.
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.
1. NanoID is Only 108 bytes in Size. Unlike UUID, NanoID is 4.5 times smaller in size and does not have any dependencies.
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 String
s 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.
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==
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With