Created
September 25, 2024 19:40
-
-
Save lmonkiewicz/a4c59f87d746e2a1fd83bbf594871a44 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; | |
public class Base64ToUUID { | |
// Method to convert UUID to base64 (without padding) | |
public static String uuidToBase64(UUID uuid) { | |
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]); | |
byteBuffer.putLong(uuid.getMostSignificantBits()); | |
byteBuffer.putLong(uuid.getLeastSignificantBits()); | |
String base64 = Base64.getEncoder().encodeToString(byteBuffer.array()); | |
return base64.replaceAll("=+$", ""); // Remove padding | |
} | |
// Method to convert base64 back to UUID | |
public static UUID base64ToUUID(String base64) { | |
// Add padding back if necessary | |
String base64WithPadding = base64; | |
while (base64WithPadding.length() % 4 != 0) { | |
base64WithPadding += "="; | |
} | |
// Decode base64 to bytes | |
byte[] bytes = Base64.getDecoder().decode(base64WithPadding); | |
// Convert bytes to most and least significant bits of UUID | |
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); | |
long mostSigBits = byteBuffer.getLong(); | |
long leastSigBits = byteBuffer.getLong(); | |
// Return the UUID | |
return new UUID(mostSigBits, leastSigBits); | |
} | |
public static void main(String[] args) { | |
// Generate a random UUID | |
UUID uuid = UUID.randomUUID(); | |
System.out.println("Original UUID: " + uuid); | |
// Convert to base64 | |
String base64UUID = uuidToBase64(uuid); | |
System.out.println("Base64 UUID (without padding): " + base64UUID); | |
// Convert back from base64 to UUID | |
UUID decodedUUID = base64ToUUID(base64UUID); | |
System.out.println("Decoded UUID: " + decodedUUID); | |
// Display the decoded UUID in hexadecimal form | |
String hexUUID = decodedUUID.toString().replace("-", ""); | |
System.out.println("UUID in Hexadecimal: " + hexUUID); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment