javabit-manipulationargb

Bit operation: inverse argb ignoring alpha


I'm new to bit operations and would like to do the following with it:
I need the argb code of an inversed color for my programm, like red becomes cyan or white becomes black. Experimenting with photoshop I found out that therefore you have to calculate 255 - red, 255 - green and 255 - blue. So this could look like this:

int getInversed(int argb) {
    Color old = new Color(argb);
    Color negative = new Color(255 - old.getRed(), 255 - old.getGreen(), 255 - old.getBlue(), old.getAlpha());
    return negative.getRGB();
}

Now I guessed that if you take the red-, green- and blue-values as 8-bit bytes, you can simply inverse them with the ~ operator to get the same result.
But I can't inverse the whole argb code, since that would also inverse alpha and I want alpha untouched:

public int getInversed(int argb) {
    return ~argb;    //inverses alpha as well
}

So how can I inverse an argb code with bit operations, ignoring the alpha part?


Solution

  • You can do it with xor mask:

    Therefore inversion of the values of bits is done by XORing them with a 1
    Also note that XOR masking is bit-safe, meaning that it will not affect unmasked bits

    return argb ^ 0x00FFFFFF;