如何在两个多头转换为字节数组=如何UUID转换为字节数组?

问题描述:

我使用的Java类 UUID ,需要一个UUID转换为字节数组。奇怪的UUID类不提供toBytes()方法。

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

可是如何才能让成字节数组吗?结果应与拖车值一个byte []。不知何故,我需要做的Bitshifting但是,怎么样?

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?

更新:

我发现:

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

这是方法corret?

Is this approach corret?

是否有任何其他的方法(用于学习目的)?

Are there any other methods (for learning purposes)?

非常感谢!
延斯

Thanks very much!! Jens

您可以使用的ByteBuffer

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