Skip to content

Instantly share code, notes, and snippets.

@akkijp
Created October 25, 2015 12:06
Show Gist options
  • Save akkijp/5e3f290f715028b49862 to your computer and use it in GitHub Desktop.
Save akkijp/5e3f290f715028b49862 to your computer and use it in GitHub Desktop.
rbgをhexに相互変換する。golang
package main
import "fmt"
func main() {
fmt.Println(dec2hex(256, 4))
fmt.Println(rgb2int(256, 256, 256))
fmt.Println(int2rgb(0))
}
func dec2hex(n, beam int) string {
hex := ""
str := "0123456789abcdef"
for i := 0; i < beam; i++ {
m := n & 0xf
hex = string(str[m]) + hex
n -= m
n >>= 4
}
return hex
}
func rgb2int(r, g, b int) int {
return (((r >> 5) << 6) | ((g >> 5) << 3) | ((b >> 5) << 0))
}
func int2rgb(i int) (r, g, b int) {
return ((i >> 6 & 0x7) << 5) + 16, ((i >> 3 & 0x7) << 5) + 16, ((i >> 0 & 0x7) << 5) + 16
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment