加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 将uuid转换为字节,当使用UUID.nameUUIDFromBytes(b)

发布时间:2020-12-14 16:18:16 所属栏目:Java 来源:网络整理
导读:我使用此代码将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 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

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读