位操作:逆 argb 忽略 alpha

Bit operation: inverse argb ignoring alpha

我是位运算的新手,想用它做以下事情:
我的程序需要反转颜色的 argb 代码,例如红色变为青色或白色变为黑色。在使用 photoshop 进行实验后我发现,因此您必须计算 255 - 红色、255 - 绿色和 255 - 蓝色。所以这看起来像这样:

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();
}

现在我猜想如果将红色、绿色和蓝色值作为 8 位 bytes,您可以简单地用 ~ 运算符将它们取反以获得相同的结果.
但我不能反转整个 argb 代码,因为那也会反转 alpha,我希望 alpha 保持不变:

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

那么如何通过位操作反转 argb 代码,忽略 alpha 部分?

你可以用 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;