我正在使用 Java
UUID
并且需要将 UUID 转换为字节数组。奇怪的是,UUID 类没有提供 "toBytes()"
方法。
我已经了解了这两种方法:
UUID.getMostSignificantBits()
and
UUID.getLeasSignificantBits()
但是如何将其放入字节数组中呢?结果应该是一个包含这两个值的 byte[] 。我不知何故需要进行位移,但是如何做?
更新:
我发现:
ByteBuffer byteBuffer = MappedByteBuffer.allocate(2);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
这种做法正确吗?
还有其他方法(用于学习目的)吗?
非常感谢!! 延斯
您可以使用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());
如果您更喜欢“常规”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();
对于任何尝试在 Java 1.7 中使用此功能的人,我发现以下内容是必要的:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(password.getMostSignificantBits());
dos.writeLong(password.getLeastSignificantBits());
dos.flush(); // May not be necessary
return baos.toByteArray();