Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Base64 UUID encoder/decoder optimised for encoding and decoding UUID hashes in only 22 characters (instead of 36)
import java.nio.ByteBuffer;
import java.util.Base64;
import java.util.UUID;
public class base64uuid {
private static final Base64.Encoder BASE64_URL_ENCODER = Base64.getUrlEncoder().withoutPadding();
public static void main(String[] args) {
try {
if (args.length < 2) {
throw new Exception("Invalid arguments");
}
final String op = args[0];
final String va = args[1];
switch (op) {
case "encode":
final UUID uuid = UUID.fromString(va);
final ByteBuffer encodeBuffer = ByteBuffer.wrap(new byte[16]);
encodeBuffer.putLong(uuid.getMostSignificantBits());
encodeBuffer.putLong(uuid.getLeastSignificantBits());
System.out.println(BASE64_URL_ENCODER.encodeToString(encodeBuffer.array()));
break;
case "decode":
final byte[] decoded = Base64.getUrlDecoder().decode(va);
final ByteBuffer decodeBuffer = ByteBuffer.wrap(decoded);
final long mostSigBits = decodeBuffer.getLong();
final long leastSigBits = decodeBuffer.getLong();
System.out.println(new UUID(mostSigBits, leastSigBits).toString());
break;
default:
throw new Exception("Invalid arguments");
}
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment