Last active
March 5, 2026 17:19
-
-
Save Nikos410/af6bf9afbf7edfa5c32c6c0907db1842 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.nio.ByteBuffer; | |
| import java.util.Base64; | |
| import java.util.UUID; | |
| class CompactUuid { | |
| public static void main(String[] args) { | |
| final UUID originalUuid = UUID.randomUUID(); | |
| System.out.println("Original: " + originalUuid); | |
| final String encoded = encode(originalUuid); | |
| System.out.println("Encoded: " + encoded); | |
| final UUID decoded = decode(encoded); | |
| System.out.println("Decoded: " + decoded); | |
| assert originalUuid.equals(decoded); | |
| } | |
| private static String encode(UUID uuid) { | |
| final long mostSignificantBits = uuid.getMostSignificantBits(); | |
| final long leastSignificantBits = uuid.getLeastSignificantBits(); | |
| final ByteBuffer inputByteBuffer = ByteBuffer.allocate(Long.BYTES * 2); | |
| inputByteBuffer.putLong(mostSignificantBits); | |
| inputByteBuffer.putLong(leastSignificantBits); | |
| final byte[] bytes = inputByteBuffer.array(); | |
| return Base64.getEncoder().encodeToString(bytes); | |
| } | |
| private static UUID decode(String base64String) { | |
| final byte[] bytes = Base64.getDecoder().decode(base64String); | |
| final ByteBuffer byteBuffer = ByteBuffer.allocate(Long.BYTES * 2); | |
| byteBuffer.put(bytes); | |
| byteBuffer.rewind(); | |
| final long mostSignificantBits = byteBuffer.getLong(); | |
| final long leastSignificantBits = byteBuffer.getLong(); | |
| return new UUID(mostSignificantBits, leastSignificantBits); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment