This article introduces several GUID generation algorithms. If you need it, you can refer to the Globally Unique Identifier (GUID, Globally Unique IDentifier), also known as UUID (Universally Unique Identifier ).
GUID is a 128-bit numeric identifier generated by an algorithm. The GUID format is "xxxxxxxx-xxxx-xxxxxxxxxxxx", where x is a 32-bit hexadecimal number in the range of 0-9 or a-f. Ideally, no computer or computer cluster generates two identical guids.
The total number of guids reaches 2 ^ 128 (3.4 × 10 ^ 38), so the probability of randomly generating two identical guids is very small, but not 0. The term GUID sometimes refers to Microsoft's UUID standard implementation.
Algorithm 1
The Code is as follows:
Function uuid (){
Var s = [];
Var hexDigits = "0123456789 abcdef ";
For (var I = 0; I <36; I ++ ){
S [I] = hexDigits. substr (Math. floor (Math. random () * 0x10), 1 );
}
S [14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
S [19] = hexDigits. substr (s [19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
S [8] = s [13] = s [18] = s [23] = "-";
Var uuid = s. join ("");
Return uuid;
}
Algorithm 2
The Code is as follows:
Function guid (){
Return 'xxxxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx '. replace (/[xy]/g, function (c ){
Var r = Math. random () * 16 | 0, v = c = 'X '? R: (r & 0x3 | 0x8 );
Return v. toString (16 );
});
}
Algorithm 3
The Code is as follows:
Function guid (){
Function S4 (){
Return (1 + Math. random () x 0x10000) | 0). toString (16). substring (1 );
}
Return (S4 () + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + "-" + S4 () + S4 () + S4 ());
}
Algorithm 4
The Code is as follows:
Function uuid (len, radix ){
Var chars = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz '. split ('');
Var uuid = [], I;
Radix = radix | chars. length;
If (len ){
// Compact form
For (I = 0; I <len; I ++) uuid [I] = chars [0 | Math. random () * radix];
} Else {
// Rfc4122, version 4 form
Var r;
// Rfc4122 requires these characters
Uuid [8] = uuid [13] = uuid [18] = uuid [23] = '-';
Uuid [14] = '4 ';
// Fill in random data. At I = 19 set the high bits of clock sequence
// Per rfc4122, sec. 4.1.5
For (I = 0; I <36; I ++ ){
If (! Uuid [I]) {
R = 0 | Math. random () * 16;
Uuid [I] = chars [(I = 19 )? (R & 0x3) | 0x8: r];
}
}
}
Return uuid. join ('');
}
You can specify the length and base number. For example
The Code is as follows:
// 8 character ID (base = 2)
Uuuid (8, 2) // "01001010"
// 8 character ID (base = 10)
Uuid (8, 10) // "47473046"
// 8 character ID (base = 16)
Uuid (8, 16) // "098F4D35"