#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
*/