Optimized UUID Storage Using Base64
The original approach of converting UUIDs to base64 and removing trailing "==" results in a 22-byte string. While this is a space-saving technique, it could potentially compromise the readability and compatibility of the UUIDs.
A more robust approach involves using a UUID library that supports converting UUIDs to a compact base64 representation. Such libraries encode the UUID's most and least significant bits into a base64 string without any unnecessary padding or trailing characters. This method typically yields a string of around 26-30 characters while preserving the human-readable format of the UUID.
An example of such a library is Apache Commons Codec, which provides the following functions:
import org.apache.commons.codec.binary.Base64; private static String uuidToBase64(String str) { Base64 base64 = new Base64(); UUID uuid = UUID.fromString(str); ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return base64.encodeBase64URLSafeString(bb.array()); } private static String uuidFromBase64(String str) { Base64 base64 = new Base64(); byte[] bytes = base64.decodeBase64(str); ByteBuffer bb = ByteBuffer.wrap(bytes); UUID uuid = new UUID(bb.getLong(), bb.getLong()); return uuid.toString(); }
Using this approach, you can convert UUIDs to base64 strings with reduced byte count while maintaining their integrity and compatibility.
The above is the detailed content of How Can I Optimize UUID Storage Using Base64 Encoding?. For more information, please follow other related articles on the PHP Chinese website!