Getting contrast color to a given color in RGB or ARGB or HEX I am looking for a stable way to find a contrast/inverted/opposite color to a given one.

Application of this is to find best possible color for foreground to give background.
I read this in a magazine article probably 25 years ago. I don't recall the full derivation, but they said to take each component (red, green, and blue) and invert the high bit of the color. In a C-like programming language, you could do:

 component = (~component &amp; 0x80) | (component &amp; 0x7F);


This can be simplified to:

component ^= 0x80;


for  a single component or to:

component ^= 0x80808000;


if you want to do 4 components at once (and don't affect the alpha).

This assumes your components are 8-bit values. This avoids the problems you get with the middle values if you simply invert them. In that case 127 becomes 128, and vice-versa. But with the above solution, 127 becomes 255 and 128 becomes 0.