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;
}
@kongk
Copy link

kongk commented May 23, 2019

Nice :-)
But I believe you will get the same result by doing:

private Long generateUniqueId() {
        long val = -1;
        do {
            val = UUID.randomUUID().getMostSignificantBits();
        } while (val < 0);
        return val;
    }

@dionys
Copy link

dionys commented Jul 2, 2019

UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE

@oavilex
Copy link

oavilex commented May 23, 2020

I try

private static Long generateUniqueId() {
    Long val = -1L;
    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() & Long.MAX_VALUE;
    return val;
}

but after 50 000 000 keys in a set its posible a collition :(

@uppersnatch
Copy link

can I get uuid back from this generated long value?

@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