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?
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;
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With