Home > Database > Mysql Tutorial > How Can I Optimize UUID Storage Using Base64 Encoding?

How Can I Optimize UUID Storage Using Base64 Encoding?

Barbara Streisand
Release: 2024-12-20 09:52:10
Original
355 people have browsed it

How Can I Optimize UUID Storage Using Base64 Encoding?

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();
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template