Last active
December 20, 2017 10:45
-
-
Save Spriithy/fc9ca56624ea659b28f65c38c39db245 to your computer and use it in GitHub Desktop.
A simple GUID generating function
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
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