Last active
October 8, 2019 22:01
-
-
Save rbobillot/610b0c31bdd4328e2a3dac5e89f7a242 to your computer and use it in GitHub Desktop.
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" | |
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