12

I am using Javas UUID and need to convert a UUID to a byte Array. Strangely the UUID Class does not provide a "toBytes()" method.

I already found out about the two methods:

UUID.getMostSignificantBits()
and
UUID.getLeasSignificantBits()

But how to get this into a byte array? the result should be a byte[] with those tow values. I somehow need to do Bitshifting but, how?

update:

I found:

 ByteBuffer byteBuffer = MappedByteBuffer.allocate(2);
 byteBuffer.putLong(uuid.getMostSignificantBits());
 byteBuffer.putLong(uuid.getLeastSignificantBits());

Is this approach corret?

Are there any other methods (for learning purposes)?

Thanks very much!! Jens

jens
  • 16,455
  • 4
  • 21
  • 20
  • The code in the update is not correct: it only allocates two bytes in the buffer but you need 16. The code in the answer below is however correct. – Jon Tirsen Jan 31 '12 at 12:17

3 Answers3

16

You can use ByteBuffer

 byte[] bytes = new byte[16];
 ByteBuffer bb = ByteBuffer.wrap(bytes);
 bb.order(ByteOrder.LITTLE_ENDIAN or ByteOrder.BIG_ENDIAN);
 bb.putLong(UUID.getMostSignificantBits());
 bb.putLong(UUID.getLeastSignificantBits());

 // to reverse
 bb.flip();
 UUID uuid = new UUID(bb.getLong(), bb.getLong());
Felix GV
  • 167
  • 1
  • 9
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
5

One option if you prefer "regular" IO to NIO:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.write(uuid.getMostSignificantBits());
dos.write(uuid.getLeastSignificantBits());
dos.flush(); // May not be necessary
byte[] data = dos.toByteArray();
Marius Soutier
  • 11,184
  • 1
  • 38
  • 48
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

For anyone trying to use this in Java 1.7, I found the following to be necessary:

<!-- language: lang-java -->
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(password.getMostSignificantBits());
dos.writeLong(password.getLeastSignificantBits());
dos.flush(); // May not be necessary
return baos.toByteArray();
John Ruiz
  • 2,371
  • 3
  • 20
  • 29