Last active
May 28, 2024 12:24
-
-
Save sixem/3ef2c2d3d211846f0f51a97508f114ae to your computer and use it in GitHub Desktop.
Simple UUIDv4 class in Java
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
import java.util.BitSet; | |
import java.security.SecureRandom; | |
public class UUIDv4 { | |
private static final boolean[] VERSION = new boolean[] { | |
false, true, false, false // Version 4 | |
}; | |
private static final boolean[] VARIANT = new boolean[] { | |
true, false // Variant | |
}; | |
private final BitSet uuid = new BitSet(128); | |
UUIDv4() { | |
SecureRandom secRand = new SecureRandom(); | |
for (int j = 0; j < 128; j++) { | |
if (j >= 48 && j < (52)) { // Set required version bits (v4) | |
uuid.set(j, VERSION[j - 48]); continue; | |
} | |
if (j >= 64 && j < (66)) { // Set required variant bits | |
uuid.set(j, VARIANT[j - 64]); continue; | |
} | |
uuid.set(j, secRand.nextBoolean()); // Generate UUID bit sequence | |
} | |
} | |
@Override | |
public String toString() { | |
StringBuilder sb = new StringBuilder(); | |
for (int j = 0; j < 8; j++) { | |
for (int k = 0; k < 4; k++) { | |
int v = 0; | |
for (int i = 0; i < 4; i++) { | |
int bit = ((j * 16) + (k * 4) + i); | |
if (uuid.get(bit)) { | |
v += (1 << (3 - i)); | |
} | |
if (i == 3) { | |
sb.append((char) ( | |
v < 10 ? '0' + v : 'a' + (v - 10) | |
)); | |
} | |
if (bit == 32 || bit == 48 || bit == 64 || bit == 80) { | |
sb.append("-"); | |
} | |
} | |
} | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment