A GUID (Globally Unique Identifier) or UUID (Universally Unique Identifier) is a 128-bit unique identifier that is used in computer systems to identify resources such as files, objects, and components. A GUID is generated randomly and is very unlikely to be duplicated. It is used in various applications and systems such as databases, web applications, and operating systems.
It is typically represented as a string of 32 hexadecimal digits, such as “550e8400-e29b-11d4-a716-446655440000”. GUIDs are generated using a combination of timestamps, random numbers, and network address information.
Syntax:
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx
Parameters:
- x – represents a hexadecimal digit (0-9, A-F).
- M – represents the version of the GUID/UUID (1-5).
- N – represents the variant of the GUID/UUID (8, 9, A, or B).
Approach
- Using a programming language: Many programming languages have built-in functions or libraries to generate GUIDs/UUIDs. For example, in C#, you can use the Guid.NewGuid() method.
- Using an online tool: There are many online GUID/UUID generators that can be used to generate a GUID/UUID. These tools are typically free and require no installation.
- Using a command-line tool: Many operating systems have built-in command-line tools that can be used to generate GUIDs/UUIDs. For example, on Windows, you can use the guidgen.exe tool.
Example 1: In this example, a concise JavaScript function generates a random UUID following the ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’ pattern. The UUID includes randomly generated hexadecimal digits, a fixed ‘4’ for version indication, and a digit following a specific pattern denoted by ‘y’. The function then prints the generated UUID to the console using console.log(random_uuid)
.
// Generate a random UUID const random_uuid = uuidv4(); // Print the UUID console.log(random_uuid); function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
.replace(/[xy]/g, function (c) {
const r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
} |
8e8679e3-02b1-410b-9399-2c1e5606a971
Example 2: In this example, a succinct JavaScript code snippet utilizes the ‘uuid’ library to generate a random UUID. The uuidv4
function from the library is assigned to random_uuid
, and the generated UUID is printed to the console with console.log(random_uuid)
. The ‘uuid’ library simplifies the process of UUID generation in a concise manner.
const { v4: uuidv4 } = require( 'uuid' );
// Generate a random UUID const random_uuid = uuidv4(); // Print the UUID console.log(random_uuid); |
Output:
93243b0e-6fbf-4a68-a6c1-6da4b4e3c3e4