Search code examples
javamathbit-manipulationbitwise-operatorsbitwise-or

Mathematical equation for OR bitwise operation?


Is there a mathematical expression for the bit-wise OR operation using basic operators such as *,+,-, and /? An example of what I am looking for would (for shifts) be n<<a turning into n*Math.pow(2,a).


Solution

  • can suggest an algorithmic solution

    public static void main(String[] args) throws Exception {
        byte a = 0x14;
        byte b = 0x1;
        int c = or(a, b);
        System.out.println(Integer.toHexString(c));
    }
    
    static int or(byte a, byte b) {
        int c = 0;
        for (int i = 0; i < 8; i++) {
            if (bit(a, i) != 0 || bit(b, i) != 0) {
                c += Math.pow(2, i);
            }
        }
        return c;
    }
    
    static int bit(int x, int i) {
        return x / (int) Math.pow(2, i) % 2;
    }
    

    it could be converted into a one-line expression but it would be too long

    int c = (a % 2 != 0 ? 1 : b % 2 !=0 ? 1 : 0) + (a % 4 / 2 != 0 ? 2 : b % 4 / 2 !=0 ? 2 : 0) ... 
    

    this is how it calculates bits

    int a0 = a % 2;
    int a1 = a % 4 / 2;
    int a2 = a % 8 / 4;
    int a3 = a % 16 / 8;
    int a4 = a % 32 / 16;
    ...