convert uuid to byte, that works when using UUID.nameUUIDFromBytes(b)

后端 未结 2 429
逝去的感伤
逝去的感伤 2020-12-29 03:46

I am converting UUID to byte using this code

public byte[] getIdAsByte(UUID uuid)
{
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.ge         


        
相关标签:
2条回答
  • 2020-12-29 04:24
    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);
    }
    
    0 讨论(0)
  • 2020-12-29 04:43

    that's because nameUUIDFromBytes constructs a specific kind of UUID (as the javadoc states).

    if you want to convert a byte[] back to a UUID, you should use the UUID constructor. Wrap a ByteBuffer around the byte[], read the 2 longs and pass them to the UUID constructor.

    0 讨论(0)
提交回复
热议问题