How to generate a UUID (Universally Unique Identifier) in C++

1 Answer

0 votes
#include <iostream>
#include <iomanip>
#include <array>
#include <random>
#include <sstream>

/*
    Generate a UUID v4 (random-based) using idiomatic C++.

    UUID layout (RFC 4122):
    - 16 bytes total
    - Version (byte 6): high nibble must be 0b0100
    - Variant (byte 8): high bits must be 0b10xx
*/

/// Generate a UUID v4 and return it as a std::string
std::string generate_uuid_v4() {
    // 128-bit UUID = 16 bytes
    std::array<unsigned char, 16> bytes{};

    // Use a high-quality random generator
    std::random_device rd;              // non-deterministic seed
    std::mt19937_64 gen(rd());          // 64-bit Mersenne Twister
    std::uniform_int_distribution<int> dist(0, 255);

    // Fill all 16 bytes with random values
    for (auto &b : bytes) {
        b = static_cast<unsigned char>(dist(gen));
    }

    // Set version (byte 6): high nibble = 0100 (version 4)
    bytes[6] = (bytes[6] & 0x0F) | 0x40;

    // Set variant (byte 8): high bits = 10xx (RFC 4122)
    bytes[8] = (bytes[8] & 0x3F) | 0x80;

    // Convert to canonical UUID string: 8-4-4-4-12 hex digits
    std::ostringstream oss;
    oss << std::hex << std::setfill('0');

    for (size_t i = 0; i < bytes.size(); ++i) {
        oss << std::setw(2) << static_cast<int>(bytes[i]);
        if (i == 3 || i == 5 || i == 7 || i == 9)
            oss << "-";
    }

    return oss.str();
}

int main() {
    std::string uuid = generate_uuid_v4();
    
    std::cout << "Generated UUID v4: " << uuid << "\n";
}


/*
run:

Generated UUID v4: 13c92d14-15c4-4732-a2b4-c164e1d9f27d

*/

 



answered Jul 14 by avibootz
...