Last active
August 13, 2019 16:57
-
-
Save pbatey/147f4842b44398e21e500c5b2dc07049 to your computer and use it in GitHub Desktop.
UUID RFC 4122 Version 4 (random) generator
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
// UUID RFC 4122 Version 4 (random) | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
| |
void random_chars(char buffer[], int len) { | |
for (int i = 0; i < len; i++) { | |
sprintf(buffer + i, "%X", rand() % 16); | |
} | |
} | |
| |
char* uuid4(char buffer[33]) { | |
char* c = buffer; | |
int i = 0; | |
random_chars(buffer + i, 8); | |
i+=8; | |
buffer[i++] = '-'; | |
random_chars(buffer + i, 4); | |
i+=4; | |
buffer[i++] = '-'; | |
buffer[i++] = '4'; // uuid version (0b0100) | |
random_chars(buffer + i, 3); | |
i+=3; | |
buffer[i++] = '-'; | |
buffer[i++] = "89AB"[rand() % 4]; // uuid variant (0b10??) | |
random_chars(buffer + i, 3); | |
i+=3; | |
buffer[i++] = '-'; | |
random_chars(buffer + i, 12); | |
i+=12; | |
buffer[i++] = 0; | |
return buffer; | |
} | |
| |
int main(int argc, char* argv[]) { | |
srand(time(NULL)); | |
char buffer[32]; | |
printf("%s", uuid4(buffer)); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment