如何将两个long转换为字节数组=如何将UUID转换为字节数组?

jen*_*ens 12 java arrays uuid long-integer

我正在使用Javas UUID并需要将UUID转换为字节数组.奇怪的是,UUID类没有提供"toBytes()"方法.

我已经发现了两种方法:

UUID.getMostSignificantBits()
and
UUID.getLeasSignificantBits()
Run Code Online (Sandbox Code Playgroud)

但是如何将其转换为字节数组呢?结果应该是带有这些两个值的byte [].我不知何故需要做Bitshifting但是,怎么样?

更新:

我发现:

 ByteBuffer byteBuffer = MappedByteBuffer.allocate(2);
 byteBuffer.putLong(uuid.getMostSignificantBits());
 byteBuffer.putLong(uuid.getLeastSignificantBits());
Run Code Online (Sandbox Code Playgroud)

这种方法是否正确?

还有其他方法(用于学习目的)吗?

非常感谢!!延

Pet*_*rey 15

你可以使用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());
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 5

如果您更喜欢"常规"IO到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();
Run Code Online (Sandbox Code Playgroud)