Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invert an RGB color in integer form?

Given an RGB color in 32-bit unsigned integer form (eg. 0xFF00FF), how would you invert it (get a negative color), without extracting its individual components using bitshift operations?

I wonder whether it's possible using just bitwise operations (AND, OR, XOR).

More precisely, what's the algorithm that uses the least number of instructions?

like image 304
skrat Avatar asked Aug 09 '13 07:08

skrat


2 Answers

I think it is so simple. You can just calculate 0xFFFFFF-YourColor. It will be the inverted color.

int neg = 0xFFFFFF - originalRGB

// optional: set alpha to 255:
int neg = (0xFFFFFF - originalRGB) | 0xFF000000;
like image 170
Ahmad Avatar answered Sep 20 '22 14:09

Ahmad


Use this method to invert each color and maintain original alpha.

int invert(int color) {
  return color ^ 0x00ffffff;
}

xor (^) with 0 returns the original value unmodified. xor with 0xff flips the bits. so in the above case we have 0xaarrggbb we are flipping/inverting r, g and b.

This should be the most efficient way to invert a color. arithmetic is (marginally) slower than this utterly simple bit-wise manipulation.

if you want to ignore original alpha, and just make it opaque, you can overwrite the alpha:

int invert(int color) {
  0xff000000 | ~color;
}

in this case we just flip every bit of color to inverse every channel including alpha, and then overwrite the alpha channel to opaque by forcing the first 8 bits high with 0xff000000.

like image 42
Andrew Gallasch Avatar answered Sep 18 '22 14:09

Andrew Gallasch