6

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.

xenoterracide
  • 16,274
  • 24
  • 118
  • 243
  • Another discussion here: http://stackoverflow.com/questions/772802/storing-uuid-as-base64-string – Stavr00 Aug 31 '15 at 13:26

2 Answers2

9

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

ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[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);
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Alexis King
  • 43,109
  • 15
  • 131
  • 205
  • I would have never thought to `toString` first but although not an explicit requirement for me, is that actually the same as Base64 encoding the raw bytes of a UUID? – xenoterracide Jan 24 '15 at 20:11
  • @xenoterracide No, it's not the same; I've updated my answer with a version that uses the raw bytes. – Alexis King Jan 24 '15 at 20:14
-1

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

}
Maxime
  • 465
  • 4
  • 15
  • 9
    I didn't down-vote your answer but to give you a hint why people might dislike it: Your approach encodes the bytes of the already encoded (hex plus some separators, then Unicode) string representation of the UUID in Base64, not the bytes of the UUID itself. Also note that since Java 1.8, there is [Base64 support in the standard library itself](http://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html) so no need for using an external library any more. – 5gon12eder Jan 24 '15 at 20:30
  • 2
    Thanks for the constructive comment @5gon12eder It makes things clearer for the rest of us, and it makes this a better environment (: – Eugenio De Hoyos Jan 16 '17 at 19:56