Skip to content

Instantly share code, notes, and snippets.

@CraigChilds94
Last active January 27, 2024 15:39
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CraigChilds94/6514edbc6a2db5e434a245487c525c75 to your computer and use it in GitHub Desktop.
Save CraigChilds94/6514edbc6a2db5e434a245487c525c75 to your computer and use it in GitHub Desktop.
Hex to RGB conversion in Go
package main
import (
"fmt"
"strconv"
)
type Hex string
type RGB struct {
Red uint8
Green uint8
Blue uint8
}
func (h Hex) toRGB() (RGB, error) {
return Hex2RGB(h)
}
func Hex2RGB(hex Hex) (RGB, error) {
var rgb RGB
values, err := strconv.ParseUint(string(hex), 16, 32)
if err != nil {
return RGB{}, err
}
rgb = RGB{
Red: uint8(values >> 16),
Green: uint8((values >> 8) & 0xFF),
Blue: uint8(values & 0xFF),
}
return rgb, nil
}
func main() {
var rgb RGB
var err error
var hex Hex = Hex("FFAAFF")
// Usage:
rgb, err = Hex2RGB(hex)
if err != nil {
panic("Couldn't convert hex to rgb")
}
fmt.Println(fmt.Sprintf("#%s = %d,%d,%d", hex, rgb.Red, rgb.Green, rgb.Blue))
// or
// Usage:
rgb, err = hex.toRGB()
if err != nil {
panic("Couldn't convert hex to rgb")
}
fmt.Println(fmt.Sprintf("#%s = %d,%d,%d", hex, rgb.Red, rgb.Green, rgb.Blue))
}
@setanarut
Copy link

// HexColor converts hex color to color.RGBA with "#FFFFFF" format
func HexColor(hex string) color.RGBA {
	values, _ := strconv.ParseUint(string(hex[1:]), 16, 32)
	return color.RGBA{R: uint8(values >> 16), G: uint8((values >> 8) & 0xFF), B: uint8(values & 0xFF), A: 255}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment