UUID Generator — C source
Generate RFC 4122 v4 UUIDs with crypto-grade randomness. Bulk generate, copy all, toggle format (uppercase / no hyphens).
This is the C implementation — the same logic the interactive tool runs, in a shareable, citable form.
/* RFC 4122 v4 UUID generator (cryptographically secure).
*
* Language: C (C11, POSIX)
* CosmoDev polyglot showcase port of the `uuid` tool.
* Ported from src/lib/uuid.ts — display source, part of CosmoDev's
* polyglot tool pages.
*
* Produces a random (v4) UUID: 36 characters, lowercase, hyphenated as
* 8-4-4-4-12 hex digits, with the RFC version (4) and variant (10xx)
* bits set. Entropy comes from /dev/urandom — the host CSPRNG on every
* POSIX system — so the "no entropy source" failure is an explicit
* error path instead of a silent fallback.
*/
#include <stdint.h>
#include <stdio.h>
/* Fill buf with 16 bytes from the OS CSPRNG; returns 0 on success. */
static int random_bytes(uint8_t buf[16])
{
FILE *f = fopen("/dev/urandom", "rb");
if (f == NULL)
return -1;
size_t got = fread(buf, 1, 16, f);
fclose(f);
return got == 16 ? 0 : -1;
}
/* Write a fresh RFC 4122 version-4 UUID into out (36 chars, no NUL). */
static void uuid_v4(char out[36])
{
uint8_t b[16];
if (random_bytes(b) != 0) {
snprintf(out, 36, "error: entropy source unavailable");
return;
}
b[6] = (uint8_t)((b[6] & 0x0f) | 0x40); /* version 4: high nibble of byte 6 */
b[8] = (uint8_t)((b[8] & 0x3f) | 0x80); /* variant : high bits of byte 8 */
/* Render lowercase hex, hyphenating at the 8-4-4-4-12 boundaries. */
static const char hex[] = "0123456789abcdef";
int p = 0;
for (int i = 0; i < 16; i++) {
if (i == 4 || i == 6 || i == 8 || i == 10)
out[p++] = '-';
out[p++] = hex[b[i] >> 4];
out[p++] = hex[b[i] & 0x0f];
}
}
int main(void)
{
char id[37];
uuid_v4(id);
id[36] = '\0';
puts(id);
return 0;
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →