BrianDonahue.dev


Home   Links   Pics

 

How to write a GUID generator

Download the code here.

   Globally Unique Identifiers (GUIDs) are common on Windows systems. They are used to identify objects that could possibly have the same names, such as Component Object Model objects (dlls), among other things. Very rarely I'm finding it necessary to write code to communicate with PCs, but it sure comes in handy to have a GUID generation function in my programs.

   A GUID is a 31-character string containing a hex string separated by dashes. Sometimes a GUID is encased in curly-braces, sometimes not. A GUID has 8 hex characters, a hyphen, two sets of four hex characters separated by hyphens, and a final sequence of 12 hex characters. It looks like this:

012345678-01234-01234-01234567890AB

   We know we have two requirements for this code. First, let's put the U in GUID, as in unique. That means generating a random number. In C, we need to 'seed' a random number with a variable value, else the system will always generate the same sequence of random numbers. It doesn't make sense, but most programmers are comfortable with the idea. What we do then is use the current time, which is a 32-bit number that holds the number of seconds between Jan 4, 1970 and right now.

//Seed the random number
srand(time(NULL));

   A handy C function that will help us make our hex string is the sprintf function. We provide a buffer for this to work in and then a format specifier. For instance, we can turn a number value into HEX characters by using the %X (upper-case) or %x (lower case) format specifier. To take it a bit further, we can tell sprintf that the result should be 4 characters in length, and that if the result is less than 4 characters in length, to pad the preceding characters with zeroes. For instance:

LONG num=3;
char output[5];
sprintf(output, "%X", num) printf("%s\n", output); <---prints "3"
sprintf(output, "%4.4X", num);
printf("%s\n", output); <---prints "0003"

  So finally, armed with this information, we use sprintf() to build our GUID, using a series of randomly-generated 32-bit numbers, each one filling 4 bytes that we can translate into HEX:

sprintf(GUIDBuf, "%4.4X%4.4X-%4.4X-%4.4X-%4.4X%4.4X%4.4X", rand(),rand(),rand(),rand(),rand(),rand(),rand());

   This may not be the absolute best way of making a GUID, but it's proved reliable enough in my network applications.

 

Back to code page