Skip to content

Instantly share code, notes, and snippets.

@htr3n
Created April 19, 2021 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save htr3n/edf78479d315c8c337722fc6bb2f5e88 to your computer and use it in GitHub Desktop.
Save htr3n/edf78479d315c8c337722fc6bb2f5e88 to your computer and use it in GitHub Desktop.
Helper class to work with Java UUID
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.UUID;
/**
* This class provides helper methods to work with UUID, for instance, converting UUID into 16-byte
* array for database column BINARY(16) and vice versa.
*/
public final class UuidUtil
{
private UuidUtil()
{
}
/**
* Convert an {@link UUID} into a 16-byte array
*
* @param uuid the input {@link UUID}
* @return a 16-byte array if succeeded, otherwise {@code null}
*/
public static byte[] asBytes(final UUID uuid)
{
if (uuid != null)
{
ByteBuffer bb = ByteBuffer.wrap(new byte[16])
.order(ByteOrder.BIG_ENDIAN) // BIG_ENDIAN is the default, explicitly set it.
.putLong(uuid.getMostSignificantBits())
.putLong(uuid.getLeastSignificantBits());
byte[] bytes = bb.array();
bb.clear();
bb = null;
return bytes;
}
return null;
}
public static UUID asUuid(final byte[] bytes)
{
if (bytes != null)
{
ByteBuffer bb = ByteBuffer.wrap(bytes);
long firstLong = bb.getLong();
long secondLong = bb.getLong();
bb = null;
return new UUID(firstLong, secondLong);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment