Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

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

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

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

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

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

prints:

1ae004cf-0f48-469f-8a94-01339afaec41
8b5d1a71-a4a0-3b46-bec3-13ab9ab12e8e
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...