将uuid转换为byte,在使用UUID.nameUUIDFromBytes(b)时有效

时间:2013-07-27 02:15:52

标签: java uuid

我正在使用此代码将UUID转换为字节

public byte[] getIdAsByte(UUID uuid)
{
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
}

但是,如果我尝试使用此功能重新创建UUID,

public UUID frombyte(byte[] b)
{
    return UUID.nameUUIDFromBytes(b);
}

它与UUID不同。来回转换randomUUID会返回两个不同的。

UUID u = UUID.randomUUID();
System.out.println(u.toString());
System.out.println(frombyte(getIdAsByte(u)).toString());

打印:

1ae004cf-0f48-469f-8a94-01339afaec41
8b5d1a71-a4a0-3b46-bec3-13ab9ab12e8e

2 个答案:

答案 0 :(得分:53)

public class UuidUtils {
  public static UUID asUuid(byte[] bytes) {
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    long firstLong = bb.getLong();
    long secondLong = bb.getLong();
    return new UUID(firstLong, secondLong);
  }

  public static byte[] asBytes(UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
  }
}
@Test
public void verifyUUIDBytesCanBeReconstructedBackToOriginalUUID() {
  UUID u = UUID.randomUUID();
  byte[] uBytes = UuidUtils.asBytes(u);
  UUID u2 = UuidUtils.asUuid(uBytes);
  Assert.assertEquals(u, u2);
}

@Test
public void verifyNameUUIDFromBytesMethodDoesNotRecreateOriginalUUID() {
  UUID u = UUID.randomUUID();
  byte[] uBytes = UuidUtils.asBytes(u);
  UUID u2 = UUID.nameUUIDFromBytes(uBytes);
  Assert.assertNotEquals(u, u2);
}

答案 1 :(得分:18)

那是因为nameUUIDFromBytes构造了一种特定类型的UUID(如javadoc所述)。

如果要将byte []转换回UUID,则应使用UUID构造函数。在byte []周围包装一个ByteBuffer,读取2个long并将它们传递给UUID构造函数。