Skip to content

Instantly share code, notes, and snippets.

@umbertogriffo
Last active March 6, 2023 08:16
Show Gist options
  • Save umbertogriffo/956f3dacc7fbeee0b65a264e8b003044 to your computer and use it in GitHub Desktop.
Save umbertogriffo/956f3dacc7fbeee0b65a264e8b003044 to your computer and use it in GitHub Desktop.
Generate Long ID from UUID
/**
* Genereate unique ID from UUID in positive space
* Reference: http://www.gregbugaj.com/?p=587
* @return long value representing UUID
*/
private Long generateUniqueId()
{
long val = -1;
do
{
final UUID uid = UUID.randomUUID();
final ByteBuffer buffer = ByteBuffer.wrap(new byte[16]);
buffer.putLong(uid.getLeastSignificantBits());
buffer.putLong(uid.getMostSignificantBits());
final BigInteger bi = new BigInteger(buffer.array());
val = bi.longValue();
}
// We also make sure that the ID is in positive space, if its not we simply repeat the process
while (val < 0);
return val;
}
@otobrglez
Copy link

@uppersnatch no. UUID operates in a bigger space than Long so when you "trim" it down you lose information that could be used to "inflate" it back again into UUID.

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