Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert two longs to a byte array = how to convert UUID to byte array?

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

like image 924
jens Avatar asked Jul 30 '11 07:07

jens


2 Answers

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());
like image 96
Peter Lawrey Avatar answered Sep 28 '22 04:09

Peter Lawrey


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();
like image 42
Jon Skeet Avatar answered Sep 28 '22 04:09

Jon Skeet