Skip to content

Instantly share code, notes, and snippets.

@jeffjohnson9046
Last active December 11, 2023 11:06
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save jeffjohnson9046/c663dd22bbe6bb0b3f5e to your computer and use it in GitHub Desktop.
Save jeffjohnson9046/c663dd22bbe6bb0b3f5e to your computer and use it in GitHub Desktop.
Convert UUID to byte array and vice versa. Useful for when UUIDs are stored in MySQL tables as VARBINARY(16)
import java.nio.ByteBuffer;
import java.util.UUID;
public class UuidAdapter {
public static byte[] getBytesFromUUID(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
public static UUID getUUIDFromBytes(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
Long high = byteBuffer.getLong();
Long low = byteBuffer.getLong();
return new UUID(high, low);
}
}
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import tds.student.performance.dao.utils.UuidAdapter;
import java.util.UUID;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/your-test-context.xml")
@TransactionConfiguration
public class UuidAdapterTest {
@Test
public void should_Get_16_Bytes_From_a_UUID() {
UUID uuid = UUID.randomUUID();
byte[] result = UuidAdapter.getBytesFromUUID(uuid);
Assert.assertEquals("Expected result to be a byte array w/16 elements.", 16, result.length);
}
@Test
public void should_Reconstruct_Same_UUID_From_Byte_Array() {
UUID uuid = UUID.randomUUID();
byte[] bytes = UuidAdapter.getBytesFromUUID(uuid);
UUID reconstructedUuid = UuidAdapter.getUUIDFromBytes(bytes);
Assert.assertEquals(uuid, reconstructedUuid);
}
@Test
public void should_Not_Generate_the_Same_UUID_From_Bytes() {
UUID uuid = UUID.fromString("9f881758-0b4a-4eaa-b59f-b6dea0934223");
byte[] result = UuidAdapter.getBytesFromUUID(uuid);
UUID newUuid = UUID.nameUUIDFromBytes(result);
Assert.assertFalse(uuid.equals(newUuid));
}
}
@omarmurcia
Copy link

Thank you, this is so useful!.

@Tool1990
Copy link

Is this working for UUID version 4? The last Test failes for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment