How to convert from HEX color to RGB in Go

2 Answers

0 votes
package main

import (
    "fmt"
    "strconv"
    "strings"
)

func hexToRGB(hex string) (int, int, int, error) {
    // Remove the '#' if it exists
    hex = strings.TrimPrefix(hex, "#")

    // Parse the R, G, and B components
    r, err := strconv.ParseInt(hex[0:2], 16, 32)
    if err != nil {
        return 0, 0, 0, err
    }
    g, err := strconv.ParseInt(hex[2:4], 16, 32)
    if err != nil {
        return 0, 0, 0, err
    }
    b, err := strconv.ParseInt(hex[4:6], 16, 32)
    if err != nil {
        return 0, 0, 0, err
    }

    return int(r), int(g), int(b), nil
}

func main() {
    hexColor := "#4CFF05"
    
    r, g, b, err := hexToRGB(hexColor)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    
    fmt.Printf("HEX: %s -> RGB: (%d, %d, %d)\n", hexColor, r, g, b)
}



/*
run:
     
HEX: #4CFF05 -> RGB: (76, 255, 5)

*/
 

 



answered Mar 6, 2025 by avibootz
0 votes
package main

import (
        "fmt"
        "strconv"
        "strings"
)

func hexToRGB(hex string) (int, int, int, error) {
        // Remove the '#' if it exists
        hex = strings.TrimPrefix(hex, "#")

        if len(hex) == 3 {
                var expandedHex strings.Builder
                for _, c := range hex {
                        expandedHex.WriteString(string(c))
                        expandedHex.WriteString(string(c))
                }
                hex = expandedHex.String()
        }

        if len(hex) != 6 {
                return 0, 0, 0, fmt.Errorf("invalid hex code length")
        }

        // Parse the R, G, and B components
        r, err := strconv.ParseInt(hex[0:2], 16, 32)
        if err != nil {
                return 0, 0, 0, err
        }
        g, err := strconv.ParseInt(hex[2:4], 16, 32)
        if err != nil {
                return 0, 0, 0, err
        }
        b, err := strconv.ParseInt(hex[4:6], 16, 32)
        if err != nil {
                return 0, 0, 0, err
        }

        return int(r), int(g), int(b), nil
}

func main() {
        hexColor1 := "#4CFF05"

        r1, g1, b1, err1 := hexToRGB(hexColor1)
        if err1 != nil {
                fmt.Println("Error:", err1)
                return
        }

        fmt.Printf("HEX: %s -> RGB: (%d, %d, %d)\n", hexColor1, r1, g1, b1)

        hexColor2 := "#f00"

        r2, g2, b2, err2 := hexToRGB(hexColor2)
        if err2 != nil {
                fmt.Println("Error:", err2)
                return
        }

        fmt.Printf("HEX: %s -> RGB: (%d, %d, %d)\n", hexColor2, r2, g2, b2)
}



/*
run:
     
HEX: #4CFF05 -> RGB: (76, 255, 5)
HEX: #f00 -> RGB: (255, 0, 0)

*/
 

 



answered Mar 7, 2025 by avibootz

Related questions

1 answer 75 views
1 answer 104 views
104 views asked Jan 27, 2025 by avibootz
1 answer 68 views
1 answer 127 views
2 answers 129 views
2 answers 98 views
2 answers 111 views
...