Skip to content

Instantly share code, notes, and snippets.

@rbobillot
Last active October 8, 2019 22:01
Show Gist options
  • Save rbobillot/610b0c31bdd4328e2a3dac5e89f7a242 to your computer and use it in GitHub Desktop.
Save rbobillot/610b0c31bdd4328e2a3dac5e89f7a242 to your computer and use it in GitHub Desktop.
package main
import "fmt"
const step int = 8
const mask int = ^(-1 << step) // NOT(-1 << 8)
type RGB struct {
Red int
Green int
Yellow int
}
func (rgb *RGB) score() int {
binarySum := 0
colors := []int{rgb.Red, rgb.Green, rgb.Yellow}
for n, color := range colors {
binarySum |= color << (step * n)
}
return binarySum
}
func getRgbFromScore(score int) RGB {
return RGB{
Red: score >> (step * 0) & mask,
Green: score >> (step * 1) & mask,
Yellow: score >> (step * 2) & mask,
}
}
func main() {
rgb1 := RGB{1,2,3}
score1 := rgb1.score()
fmt.Println(score1) // 197121
fmt.Println(getRgbFromScore(score1)) // {1 2 3}
rgb2 := RGB{3,2,1}
score2 := rgb2.score()
fmt.Println(score2) // 66051
fmt.Println(getRgbFromScore(score2)) // {3 2 1}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment