Last active
May 18, 2025 11:47
-
-
Save Genzer/4f8e73706bf6d6b3983572589c126260 to your computer and use it in GitHub Desktop.
Shorten an UUIDv4 by encoding in Base64
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.util.UUID; | |
import java.util.Base64; | |
import java.nio.ByteBuffer; | |
import java.nio.ByteOrder; | |
public class UuidShortener { | |
/* NOTE: | |
* The implementation was mostly copied from StackOverflow [1], | |
* as well as the hint of using BIG_ENDIAN [2]. | |
* | |
* [1]: https://stackoverflow.com/a/29836273/495558 | |
* [2]: https://stackoverflow.com/a/40297651/495558 | |
*/ | |
public static String shorten(UUID uuid) { | |
ByteBuffer bb = ByteBuffer.allocate(16) // UUIDv4 is a 128-bit octet. | |
.order(ByteOrder.BIG_ENDIAN) // UUID Standard uses big-endian for binary presentation. | |
.putLong(uuid.getMostSignificantBits()) | |
.putLong(uuid.getLeastSignificantBits()); | |
return Base64.getUrlEncoder().withoutPadding().encodeToString(bb.array()); | |
} | |
public static UUID restore(String shortenUuid) { | |
byte[] octets = Base64.getUrlDecoder().decode(shortenUuid); | |
ByteBuffer bb = ByteBuffer.wrap(octets); | |
long mostSigBits = bb.getLong(); | |
long leastSigBits = bb.getLong(); | |
return new UUID(mostSigBits, leastSigBits); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment