I want to generate guids to insert into a SQLite database (i.e. no support from the db itself). However, I would like to have control over certain properties:
One place to look for an answer to creating a GUID that contains many of the elements the author is looking for is in PHP .. http://us3.php.net/uniqid .. In their examples, they discuss how to add server names, database names, and other elements to a GUID.
However, to address the need for a C based GUID function, here is code based on a JavaScript function .. Create GUID / UUID in JavaScript? .. this example uses RegEx to create the GUID.
Below is code that will create a GUID based on the JavaSCript example. I'm sure there are more elegant solutions out there. This is something cobbled together to help give a clean example for others to follow.
srand (clock());
char GUID[40];
int t = 0;
char *szTemp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
char *szHex = "0123456789ABCDEF-";
int nLen = strlen (szTemp);
for (t=0; t<nLen+1; t++)
{
int r = rand () % 16;
char c = ' ';
switch (szTemp[t])
{
case 'x' : { c = szHex [r]; } break;
case 'y' : { c = szHex [r & 0x03 | 0x08]; } break;
case '-' : { c = '-'; } break;
case '4' : { c = '4'; } break;
}
GUID[t] = ( t < nLen ) ? c : 0x00;
}
printf ("%s\r\n", GUID);
Note: strings end with a 0x00 character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With