Logo

Programming-Idioms

  • Rust
  • Go

Idiom #154 Halfway between two hex color codes

Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.

import "fmt"
import "strconv"
var buf [7]byte
buf[0] = '#'
for i := 0; i < 3; i++ {
	sub1 := c1[1+2*i : 3+2*i]
	sub2 := c2[1+2*i : 3+2*i]
	v1, _ := strconv.ParseInt(sub1, 16, 0)
	v2, _ := strconv.ParseInt(sub2, 16, 0)
	v := (v1 + v2) / 2
	sub := fmt.Sprintf("%02X", v)
	copy(buf[1+2*i:3+2*i], sub)
}
c := string(buf[:])

Loops over each component r, g, b.

For conciseness this assumes that input validity has already been checked, so we omit some returned errors.
import "fmt"
import "strconv"
r1, _ := strconv.ParseInt(c1[1:3], 16, 0)
r2, _ := strconv.ParseInt(c2[1:3], 16, 0)
r := (r1 + r2) / 2

g1, _ := strconv.ParseInt(c1[3:5], 16, 0)
g2, _ := strconv.ParseInt(c2[3:5], 16, 0)
g := (g1 + g2) / 2

b1, _ := strconv.ParseInt(c1[5:7], 16, 0)
b2, _ := strconv.ParseInt(c2[5:7], 16, 0)
b := (b1 + b2) / 2

c := fmt.Sprintf("#%02X%02X%02X", r, g, b)

For conciseness this assumes that input validity has already been checked, so we omit some returned errors.
use std::str::FromStr;
use std::fmt;
"Too long for text box, see online demo"
using System.Drawing;
Color color1 = ColorTranslator.FromHtml(c1);
Color color2 = ColorTranslator.FromHtml(c2);
c = string.Format($"#{((color1.R + color2.R) / 2):X2}{((color1.G + color2.G) / 2):X2}{((color1.B + color2.B) / 2):X2}");

New implementation...
< >
programming-idioms.org