Last active
March 6, 2023 08:16
-
-
Save umbertogriffo/956f3dacc7fbeee0b65a264e8b003044 to your computer and use it in GitHub Desktop.
Generate Long ID from UUID
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
UUID.randomUUID().getMostSignificantBits() & Long.MAX_VALUE
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 :(
can I get uuid back from this generated long value?
@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
Nice :-)
But I believe you will get the same result by doing: