Last active
September 13, 2024 06:04
-
-
Save CraigChilds94/6514edbc6a2db5e434a245487c525c75 to your computer and use it in GitHub Desktop.
Hex to RGB conversion in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
commented
Dec 31, 2023
thanks guys this really has helped ya junior
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment