How to generate a random color in HEX format with Go

2 Answers

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func generateRandomNumber(min, max int) int {
    return rand.Intn(max-min+1) + min
}

func generateRandomRGBColor() {
    red := generateRandomNumber(0, 255)
    green := generateRandomNumber(0, 255)
    blue := generateRandomNumber(0, 255)

    fmt.Printf("Random RGB Color: rgb(%d, %d, %d)\n", red, green, blue)
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed the random number generator
    
    generateRandomRGBColor()
}



/*
run:

Random RGB Color: rgb(214, 245, 172)

*/

 



answered Oct 9, 2025 by avibootz
0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

/*
    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.Intn(n) returns a value in [0, n),
   so using 0x1000000 (2^24) gives exactly 24 bits.
*/
func randomColorInt() int {
    // 24 bits → values from 0 to 16,777,215 (0xFFFFFF)
    return rand.Intn(0x1000000)
}

/*
   Convert a 24‑bit integer into a hex color string.
   %06X ensures exactly 6 uppercase hex digits.
*/
func intToHexColor(value int) string {
    return fmt.Sprintf("#%06X", value)
}

/*
   Produce a random hex color by combining the two functions.
*/
func generateRandomHexColor() (int, string) {
    value := randomColorInt()      // 24‑bit random number
    hex := intToHexColor(value)    // Convert to #RRGGBB
    return value, hex
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed RNG

    value, hex := generateRandomHexColor()

    fmt.Println("Random 24‑bit value:", value)
    fmt.Println("Hex color:", hex)
}


/*
run:

Random 24‑bit value: 6774407
Hex color: #675E87

*/

 



answered Aug 23 by avibootz
...