Home >Database >Mysql Tutorial >Is Base64 Encoding an Efficient Method for Compact UUID Storage?

Is Base64 Encoding an Efficient Method for Compact UUID Storage?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-27 09:00:17358browse

Is Base64 Encoding an Efficient Method for Compact UUID Storage?

Base64 Encoding for Compact UUID Storage

Question:

Is there any issue with storing a UUID as a base64 string with trailing "==" characters removed to minimize space?

Answer:

Base64 encoding can effectively minimize the size of a UUID while maintaining readability. However, it's essential to decode the string correctly to recover the original UUID.

Here's a practical implementation in Java:

import org.apache.commons.codec.binary.Base64;

public class UUIDBase64 {

    public static String uuidToBase64(String uuid) {
        UUID myUUID = UUID.fromString(uuid);
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(myUUID.getMostSignificantBits());
        bb.putLong(myUUID.getLeastSignificantBits());
        return new Base64().encodeBase64URLSafeString(bb.array());
    }

    public static String uuidFromBase64(String base64UUID) {
        Base64 base64 = new Base64(); 
        byte[] bytes = base64.decodeBase64(base64UUID);
        ByteBuffer bb = ByteBuffer.wrap(bytes);
        UUID myUUID = new UUID(bb.getLong(), bb.getLong());
        return myUUID.toString();
    }
}

Usage:

String uuid = "6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8";
String base64UUID = UUIDBase64.uuidToBase64(uuid);
System.out.println("Base64 UUID: " + base64UUID);
String decodedUUID = UUIDBase64.uuidFromBase64(base64UUID);
System.out.println("Decoded UUID: " + decodedUUID);
System.out.println("Equal?: " + uuid.equals(decodedUUID));

This approach removes trailing "==" padding to produce a compact 22-character string that can be easily decoded back to the original UUID.

The above is the detailed content of Is Base64 Encoding an Efficient Method for Compact UUID Storage?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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