/**
* 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).
* random_int() provides cryptographically secure randomness.
* 0x1000000 = 2^24, giving us exactly 24 bits of color data.
*/
function randomColorInt(): int {
// 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
return random_int(0, 0xFFFFFF);
}
/**
* Convert a 24‑bit integer into a hex color string.
* sprintf("%06X") ensures exactly 6 uppercase hex digits.
*/
function intToHexColor(int $value): string {
$hex = sprintf("%06X", $value); // Convert to 6‑digit hex
return "#{$hex}";
}
/**
* Produce a random hex color by combining the two functions.
*/
function generateRandomHexColor(): array {
$value = randomColorInt(); // 24‑bit random number
$hex = intToHexColor($value); // Convert to #RRGGBB
return [
'value' => $value,
'hex' => $hex
];
}
// Run the program
$result = generateRandomHexColor();
echo "Random 24‑bit value: {$result['value']}\n";
echo "Hex color: {$result['hex']}\n";
/*
run:
Random 24‑bit value: 14657487
Hex color: #DFA7CF
*/