Skip to content

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++ (C++17)
// 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 std::random_device, which every
// mainstream standard library backs with the host CSPRNG
// (arc4random / BCryptGenRandom / RDRAND).

#include <array>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <random>
#include <sstream>
#include <string>

// Return a freshly generated RFC 4122 version-4 UUID string.
std::string uuid_v4()
{
    // One random_device draw per byte keeps the entropy source explicit;
    // each call pulls fresh bytes from the OS CSPRNG.
    static std::random_device csprng;
    std::array<uint8_t, 16> b;
    for (auto &byte : b)
        byte = static_cast<uint8_t>(csprng());

    b[6] = static_cast<uint8_t>((b[6] & 0x0f) | 0x40); // version 4
    b[8] = static_cast<uint8_t>((b[8] & 0x3f) | 0x80); // variant 10xx

    // Lowercase hex, hyphens at the 8-4-4-4-12 boundaries.
    std::ostringstream out;
    for (int i = 0; i < 16; i++) {
        if (i == 4 || i == 6 || i == 8 || i == 10)
            out << '-';
        out << std::hex << std::setfill('0') << std::setw(2)
            << static_cast<int>(b[i]);
    }
    return out.str();
}

int main()
{
    std::cout << uuid_v4() << '\n';
    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 →