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
This also means that one can (in theory) guarantee that some two inputs out there can wind up with the same UUID, and as a result, UUIDs are not generally reversible (however, in specific (limited) cases, perhaps they could be made reversible).
The str() function is used to typecast different objects to a string. We can use this function to convert UUID to String in Python. In the above example, We create a uuid object using the uuid1() function.
You can use base64 encoding and reduce it to 22 characters. If you use base94 you can get it does to 20 characters. If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes. If you don't care about Strings you can use 16, 8-bit bytes.
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With