将uuid转换为byte,在使用UUID.nameUUIDFromBytes(b)时有效 [英] convert uuid to byte, that works when using UUID.nameUUIDFromBytes(b)

查看:456
本文介绍了将uuid转换为byte,在使用UUID.nameUUIDFromBytes(b)时有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am converting UUID to byte using this code

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

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

However, if I try to recreate the UUID using this function,

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

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

It is not the same UUID. Converting a randomUUID back and forth returns two different it.

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

这篇关于将uuid转换为byte,在使用UUID.nameUUIDFromBytes(b)时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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