Skip to content

Instantly share code, notes, and snippets.

@Spriithy
Last active December 20, 2017 10:45
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 Spriithy/fc9ca56624ea659b28f65c38c39db245 to your computer and use it in GitHub Desktop.
Save Spriithy/fc9ca56624ea659b28f65c38c39db245 to your computer and use it in GitHub Desktop.
A simple GUID generating function
public class GUIDFactory {
private static final String chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int charsCount = chars.length();
/**
* Generates a random GUID. Example :
*
* <pre>
* 13219ec0-3a81-44c5-a300-de14b7d0235f
* </pre>
*
* @return A global unique identifier as a String
*/
public static String next(int length) {
String guid = "";
int cmp = 0;
for (int i = 0; i < length; i++) {
cmp = (int) (Math.round(Math.random() * 255) - 128) & 255;
if (i == 6) {
cmp = cmp & (charsCount - 1);
cmp = cmp | (4 << 4);
}
if (i == 8) {
cmp = cmp & 63;
cmp = cmp | 128;
}
guid += chars.charAt(cmp >> 4);
guid += chars.charAt(cmp & (charsCount - 1));
}
return guid;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment