/**
* 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).
* Math.random() gives a floating‑point number in [0, 1),
* so multiplying by 0x1000000 (2^24) gives a range of 24 bits.
*/
function randomColorInt() {
// 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
return Math.floor(Math.random() * 0x1000000);
}
/**
* Convert a 24‑bit integer into a hex color string.
* padStart(6, "0") ensures the hex string is always 6 characters.
*/
function intToHexColor(intValue) {
// Convert number → hex string (e.g., "3fa2c")
const hex = intValue.toString(16);
// Ensure 6 hex digits (e.g., "003fa2c")
const padded = hex.padStart(6, "0");
// Add the leading "#"
return `#${padded}`;
}
/**
* Produce a random hex color by combining the two functions.
*/
function generateRandomHexColor() {
const value = randomColorInt(); // 24‑bit random number
const hexColor = intToHexColor(value); // Convert to #RRGGBB
return { value, hexColor };
}
// Run the program
const result = generateRandomHexColor();
console.log("Random 24‑bit value:", result.value);
console.log("Hex color:", result.hexColor);
/*
run:
Random 24‑bit value: 8950214
Hex color: #8891c6
*/