Search code examples
javabytebitxor

What is the fastest method for specific bit operations between two bytes?


I have two java byte variables, lets say

a = 00010011 
b = 01101101 (in binary form)

Suppose that I have a third byte

c = 11001000

where its bits will work as an indicator to select between two operations (XOR/XNOR).

e.g. if c[i] = 1 then I select to XOR a[i]^b[i] and if c[i] = 0 I select to XNOR these values.

In this example the resulted byte will be

d = 01001001

What is the fastest method in Java to achieve such a result?


Solution

  • How about

    d = a ^ b ^ ~c;
    

    or

    d = ~(a ^ b ^ c);
    

    or

    d = ~a ^ b ^ c;
    

    The ^ has the property of flipping bits set to 1 and leaving bits set to 0. If you use ~ to flip that value you get flip for 0 and unchanged for 1.