Skip to content

Instantly share code, notes, and snippets.

@hfreire
Created May 8, 2019 10:12
Show Gist options
  • Save hfreire/3de863d28fb7020cfa19ce8eca77f7f4 to your computer and use it in GitHub Desktop.
Save hfreire/3de863d28fb7020cfa19ce8eca77f7f4 to your computer and use it in GitHub Desktop.
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