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

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

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

    UUID v4 rules (RFC 4122):
    - 16 bytes total
    - Version (byte 6): high nibble must be 0100 (version 4)
    - Variant (byte 8): high bits must be 10xx (RFC 4122 variant)
*/

/// Fill a 16-byte array with random values (0–255)
void generate_random_bytes(unsigned char b[16]) {
    for (int i = 0; i < 16; i++)
        b[i] = rand() % 256;
}

/// Apply UUID v4 rules to the random bytes
void apply_uuid_v4_rules(unsigned char b[16]) {
    // Version 4: high nibble = 0100
    b[6] = (b[6] & 0x0F) | 0x40;

    // Variant: high bits = 10xx
    b[8] = (b[8] & 0x3F) | 0x80;
}

/// Convert the 16 bytes into canonical UUID string format
void uuid_to_string(const unsigned char b[16], char out[37]) {
    sprintf(out,
        "%02x%02x%02x%02x-"
        "%02x%02x-"
        "%02x%02x-"
        "%02x%02x-"
        "%02x%02x%02x%02x%02x%02x",
        b[0], b[1], b[2], b[3],
        b[4], b[5],
        b[6], b[7],
        b[8], b[9],
        b[10], b[11], b[12], b[13], b[14], b[15]
    );
}

/// High-level UUID v4 generator
void generate_uuid_v4(char out[37]) {
    unsigned char bytes[16];
    generate_random_bytes(bytes);
    apply_uuid_v4_rules(bytes);
    uuid_to_string(bytes, out);
}

int main(void) {
    srand((unsigned)time(NULL));  // Seed RNG once

    char uuid[37];
    generate_uuid_v4(uuid);

    printf("Generated UUID v4: %s\n", uuid);
    
    return 0;
}



/*
run:

Generated UUID v4: fbeed62a-1f7e-4804-ab8d-8e4725d499f5

*/

 



answered 5 hours ago by avibootz
...