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?
Your question is unclear; no colors in RGB are "negative colors".
You could invert an image, as though it was a film negative. Is that what you meant?
If you wanted to invert an image that has just one pixel of color
0xFF00FF
, the calculation is to subtract from white,0xFFFFFF
.In a computer, a subtraction is done by adding the compliment: http://en.wikipedia.org/wiki/Method_of_complements#Binary_example
But seriously, why wouldn't you just let the machine do the subtraction for you with your ordinary code? Its what they're good at.
Use this method to invert each color and maintain original alpha.
xor (
^
) with 0 returns the original value unmodified. xor with0xff
flips the bits. so in the above case we have0xaarrggbb
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:
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
.I think it is so simple. You can just calculate 0xFFFFFF-YourColor. It will be the inverted color.
You could simply perform the negation of the color. Snippet: