0

Is it possible to calculate the difference between two hex codes? I have been searching for hours and I'm starting to think it's not possible.

Example: Color #1: #c60f13 Color #2: #970b0e Difference: 25% Darker

Oh yeah, I came across a Javascript calculator, but it didn't work.

Thanks guys!

  • 2
    This question can help you a bit : http://stackoverflow.com/questions/9820655/how-can-i-establish-the-difference-between-two-hex-colours – Egalitarian Jul 19 '13 at 19:24
  • That's the script I was talking about. For some odd reason, it isn't working for me. –  Jul 19 '13 at 19:27

4 Answers4

2

Separate them into (3) 2-byte groups, do the math for each group individually and apply that to the color that the group represents (Red / Green / Blue).

C6 - 97 = red diff
0F - 0B = green diff
13 - 03 = blue diff
DevlshOne
  • 8,357
  • 1
  • 29
  • 37
  • Awesome! Will definitely try this out. –  Jul 19 '13 at 19:29
  • The difference is #2f45. Let's say I want to make color #1 lighter by #2f45, how would that work? –  Jul 19 '13 at 19:41
1

HEX numbers and HEX RGB colors are not equal. However they are both numbers, HEX representation of RGB values contains 3 independent components: Red, Green and Blue, packed as 3x8bit components like #RRGGBB. This way we can store them as a single integer.

First you need to unpack the individual components, this way:

r = (HEX >> 16) & 0xFF
g = (HEX >> 8)  & 0xFF
b =  HEX        & 0xFF

Now you can perform the calculations

_r = abs(r1 - r2)
_g = abs(g1 - g2)
_b = abs(b1 - b2)

then repack them:

HEX = _r<<16 | _g<<8 | _b
plasmacel
  • 8,183
  • 7
  • 53
  • 101
1

I'm assuming you want the resulting color value of the difference. Also, because you tagged this with a tag, I am going to assume your are using the less css preprocessor, and if so, it already has a function for this: difference(). So it is just this:

difference(#c60f13, #970b0e);

Which produces this:

#2f0405
ScottS
  • 71,703
  • 13
  • 126
  • 146
0

You can just subtract them directly as hexadecimal values.

  0xc60f13
- 0x970b0e
----------
= 0x2F0405

If you first split them up in groups you would get the same result:

  c6   0f   13
 -97  -0b  -0e
 -------------
 =2F  =04  =05

So there is no need to do this first.

In JavaScript you can this calculation like this:

var val1 = 0xc60f13;
var val2 = 0x970b0e;
var diff = (val1 - val2) & 0xffffff;

console.log(diff.toString(16));

Result:

2f0405
Mike-O
  • 844
  • 1
  • 11
  • 16