How to generate a random color in HEX format with C

3 Answers

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

// Function to generate a random number between min and max (inclusive)
int generateRandomNumber(int min, int max) {
    return rand() % (max - min + 1) + min;
}

// Function to generate a random RGB color and print its HEX code
void generateRandomRGBColor() {
    int red = generateRandomNumber(0, 255);
    int green = generateRandomNumber(0, 255);
    int blue = generateRandomNumber(0, 255);

    // Print HEX color code with leading zeros
    printf("HEX Color Code: #%02x%02x%02x\n", red, green, blue);
}

int main() {
    // Seed the random number generator
    srand((unsigned int)time(NULL));

    generateRandomRGBColor();
    
    return 0;
}



/*
run:

HEX Color Code: #e8f78b

*/

 



answered Oct 8, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void generateRandomHEXColorCode(char hex[]) {
   const char hexChars[] = "0123456789ABCDEF";
    
   for (int i = 0; i < 6; i++) {
       hex[i] = hexChars[rand() % 16]; 
   }
}
 
int main() {
   char hex[7] = {0}; 
    
   srand(time(0)); 
    
   generateRandomHEXColorCode(hex);
    
   printf("Random HEX Color: #%s\n", hex);
}
 
 
 
/*
run:
 
Random HEX Color: #AD7D81
 
*/

 



answered Oct 9, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

/*
    Generate a random color in HEX format (#RRGGBB).
    This program demonstrates how numbers and bits are used
    to produce a valid 24‑bit color value.
*/

/**
 * Create a 24‑bit random integer (0x000000–0xFFFFFF).
 * rand() produces an integer in [0, RAND_MAX].
 * We scale it down using modulo to fit exactly 24 bits.
 */
unsigned int randomColorInt(void) {
    // 24 bits → values from 0 to 16,777,215 (0xFFFFFF)

    return rand() % 0x1000000;   // 0x1000000 = 2^24
}

/**
 * Convert a 24‑bit integer into a hex color string.
 * snprintf ensures safe formatting and exactly 6 hex digits.
 */
void intToHexColor(unsigned int value, char *buffer) {
    // Format: #RRGGBB
    snprintf(buffer, 8, "#%06X");
}

/**
 * Produce a random hex color by combining the two functions.
 */
void generateRandomHexColor(unsigned int *valueOut, char *hexOut) {
    *valueOut = randomColorInt();      // 24‑bit random number
    intToHexColor(*valueOut, hexOut);  // Convert to #RRGGBB
}

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

    unsigned int value;
    char hexColor[8];                  // "#RRGGBB" + null terminator

    generateRandomHexColor(&value, hexColor);

    printf("Random 24‑bit value: %u\n", value);
    printf("Hex color: %s\n", hexColor);

    return 0;
}


/*
run:

Random 24‑bit value: 4551270
Hex color: #548E41

*/

 



answered Aug 23 by avibootz
...