如何在两个多头转换为字节数组=如何UUID转换为字节数组? [英] How to convert two longs to a byte array = how to convert UUID to byte array?

查看:896
本文介绍了如何在两个多头转换为字节数组=如何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());

这篇关于如何在两个多头转换为字节数组=如何UUID转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆