# 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(0x1000000) returns a number in [0, 0x1000000),
# giving exactly 24 bits of color data.
def random_color_int
# 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
rand(0x1000000)
end
# Convert a 24‑bit integer into a hex color string.
# "%06X" ensures exactly 6 uppercase hex digits.
def int_to_hex_color(value)
"##{format('%06X', value)}"
end
# Produce a random hex color by combining the two functions.
def generate_random_hex_color
value = random_color_int # 24‑bit random number
hex = int_to_hex_color(value) # Convert to #RRGGBB
{ value: value, hex: hex }
end
# Run the program
result = generate_random_hex_color
puts "Random 24‑bit value: #{result[:value]}"
puts "Hex color: #{result[:hex]}"
=begin
run:
Random 24‑bit value: 16747257
Hex color: #FF8AF9
=end