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

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


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


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 necessarybyte[] data = dos.toByteArray();


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 necessaryreturn baos.toByteArray();