/**
* 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(): number {
// 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(value: number): string {
const hex: string = value.toString(16); // Convert number → hex
const padded: string = hex.padStart(6, "0"); // Ensure 6 hex digits
return `#${padded}`;
}
/**
* Produce a random hex color by combining the two functions.
*/
function generateRandomHexColor(): { value: number; hex: string } {
const value: number = randomColorInt(); // 24‑bit random number
const hex: string = intToHexColor(value); // Convert to #RRGGBB
return { value, hex };
}
// Run the program
const result = generateRandomHexColor();
console.log("Random 24‑bit value:", result.value);
console.log("Hex color:", result.hex);
/*
run:
Random 24‑bit value: 16130932
Hex color: #f62374
*/