Storing UUID as base64 String

后端 未结 8 1394
青春惊慌失措
青春惊慌失措 2020-11-29 16:14

I have been experimenting with using UUIDs as database keys. I want to take up the least amount of bytes as possible, while still keeping the UUID representation human read

8条回答
  •  难免孤独
    2020-11-29 16:46

    I was also trying to do something similar. I am working with a Java application which uses UUIDs of the form 6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8 (which are generated with the standard UUID lib in Java). In my case I needed to be able to get this UUID down to 30 characters or less. I used Base64 and these are my convenience functions. Hopefully they will be helpful for someone as the solution was not obvious to me right away.

    Usage:

    String uuid_str = "6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8";
    String uuid_as_64 = uuidToBase64(uuid_str);
    System.out.println("as base64: "+uuid_as_64);
    System.out.println("as uuid: "+uuidFromBase64(uuid_as_64));
    

    Output:

    as base64: b8tRS7h4TJ2Vt43Dp85v2A
    as uuid  : 6fcb514b-b878-4c9d-95b7-8dc3a7ce6fd8
    

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

提交回复
热议问题