Logo

Programming-Idioms

History of Idiom 154 > diff from v6 to v7

Edit summary for version 7 by programming-idioms.org:
New Java implementation by user [programming-idioms.org]

Version 6

2016-10-30, 21:44:51

Version 7

2016-10-30, 21:46:24

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 # .

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 # .

Extra Keywords
hexa hexadecimal css avg mean
Extra Keywords
hexa hexadecimal css avg mean
Code
StringBuilder sb = new StringBuilder("#");
for(int i=0;i<3;i++) {
  String sub1 = c1.substring(1+2*i,3+2*i);
  String sub2 = c2.substring(1+2*i,3+2*i);
  int v1 = Integer.parseInt(sub1, 16);
  int v2 = Integer.parseInt(sub2, 16);
  int v = (v1 + v2)/2;
  String sub = String.format("%02X", v);
  sb.append(sub);
}
String c = sb.toString();
Comments bubble
Loops over each component r, g, b.