How can I convert a UUID to base64?

允我心安 提交于 2020-01-13 12:14:07

问题


I want to take type UUID and output it in a Base64 encoded format, however given the input methods on Base64 and outputs on UUID how to accomplish this doesn't seem obvious.

update though not an explicit requirement for my use case, it would be nice to know if the method used uses the raw UUID (the 128 bits that a UUID actually is) of the UUID, as the standard hex encoding does.


回答1:


First, convert your UUID to a byte buffer for consumption by a Base64 encoder:

ByteBuffer uuidBytes = ByteBuffer.wrap(new bytes[16]);
uuidBytes.putLong(uuid.getMostSignificantBits());
uuidBytes.putLong(uuid.getLeastSignificantBits());

Then encode that using the encoder:

byte[] encoded = encoder.encode(uuidBytes);

Alternatively, you can get a Base64-encoded string like this:

String encoded = encoder.encodeToString(uuidBytes);



回答2:


You can use Base64 from apache commons codecs. https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

import java.util.UUID;
import org.apache.commons.codec.binary.Base64;

public class Test {

    public static void main(String[] args) {
        String uid = UUID.randomUUID().toString();
        System.out.println(uid);
        byte[] b = Base64.encodeBase64(uid.getBytes());
        System.out.println(new String(b));
    }

}


来源:https://stackoverflow.com/questions/28129639/how-can-i-convert-a-uuid-to-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!