Skip to content

Instantly share code, notes, and snippets.

@raychenon
Last active June 1, 2018 22:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raychenon/12be57dca64b50a71205895a0bcc8d4d to your computer and use it in GitHub Desktop.
Save raychenon/12be57dca64b50a71205895a0bcc8d4d to your computer and use it in GitHub Desktop.
Convert decimal to hex https://play.golang.org/p/JxnGqpuY8P9
package main
import (
"fmt"
"strconv"
"strings"
)
func dec2hex(dec int) string {
color := dec * 255 / 100
return fmt.Sprintf("%02x", color)
}
func hex2dec(hex string) int64 {
dec, _ := strconv.ParseInt("0x"+hex, 0, 16)
dec = dec * 100 / 255
return dec
}
func main() {
for i := 0; i <= 100; i++ {
var hexa string = strings.ToUpper(dec2hex(i))
fmt.Printf("%d %% \t => '%s'\n", i, hexa)
// look further use with "hex2dec"
// Notice that the conversion from Hexa to decimal is lower than the initial value
// due to round down
// fmt.Printf("%d %% to hexa \t => '%s' \t => %d \n", i, hexa, hex2dec(hexa))
}
}
@raychenon
Copy link
Author

raychenon commented Jun 1, 2018

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