How to generate a random color in RGB format with Go

2 Answers

0 votes
package main

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

func generateRandomHexColor() string {
    const hexChars = "0123456789ABCDEF"
    hex := make([]byte, 6)

    for i := 0; i < 6; i++ {
        index := rand.Intn(16)
        hex[i] = hexChars[index]
    }

    return string(hex)
}

func main() {
    rand.Seed(time.Now().UnixNano()) // Seed the random number generator
    
    hexColor := generateRandomHexColor()
    
    fmt.Printf("Random HEX Color: #%s\n", hexColor)
}



/*
run:

Random HEX Color: #3A05F1

*/

 



answered Oct 10, 2025 by avibootz
0 votes
package main

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

/*
    Generate a random color in RGB format: rgb(R, G, B)
    This program demonstrates how numbers and bits are used
    to produce valid 8‑bit channel values.
*/

/*
   Create a random 8‑bit integer (0–255).
   rand.Intn(256) returns a value in [0, 256),
   giving exactly one byte of color data.
*/
func randomChannel() int {
    // 8 bits → values from 0 to 255
    return rand.Intn(256)
}

/*
   Produce a random RGB color by combining the channels.
*/
func generateRandomRGB() (int, int, int, string) {
    r := randomChannel() // Red channel (8 bits)
    g := randomChannel() // Green channel (8 bits)
    b := randomChannel() // Blue channel (8 bits)

    // Construct the CSS-style RGB string
    rgb := fmt.Sprintf("rgb(%d, %d, %d)", r, g, b)

    return r, g, b, rgb
}

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

    r, g, b, rgb := generateRandomRGB()

    fmt.Println("Red (8 bits):", r)
    fmt.Println("Green (8 bits):", g)
    fmt.Println("Blue (8 bits):", b)
    fmt.Println("RGB color:", rgb)
}


/*
run:

Red (8 bits): 61
Green (8 bits): 241
Blue (8 bits): 58
RGB color: rgb(61, 241, 58)

*/

 



answered Aug 23 by avibootz
...