1
0

Bitwise Operators in Java

The Java programming language also provides operators that perform bitwise and bit shift operations on integer-type variables. The operators discussed in this article are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.

The unary bitwise complement operator “~” inverts a bit pattern; it can be applied to any of the integer type variables, making every “0” a “1” and every “1” a “0”. For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is “00111100” would change its pattern to “11000011” after inversion.

The signed left shift operator “<<” shifts a bit pattern to the left, and the signed right shift operator”>>” shifts a bit pattern to the right. The bit pattern is given by the left-hand operand and the number of positions to shift by the right-hand operand. The logical shift operator “>>>” shifts a zero into the leftmost position, while the leftmost position after arithmetic right shift “>>” depends on the sign bit.

~ Bitwise unary NOT  
| Bitwise OR |=Bitwise OR assignment
& Bitwise AND &= Bitwise AND assignment
^ Bitwise exclusive OR ^= Bitwise exclusive OR assignment
>> Shift right >>= Shift right assignment
<< Shift left <<= Shift left assignment
>>> Shift right zero fill >>>= Shift right zero fill assignment

Program using the bitwise AND operator to print the number “2” to standard output.

class BitDemo
{
    public static void main(String[] args)
    {
        int bitmask = 0x000F;
        int val = 0x2222;
        System.out.println(val & bitmask); // prints "2"
    }
}

Program to demonstrate the bitwise logical operators

class BitLogic
{
    public static void main(String args[])
    {
        String binary[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
        int a = 3; // 0 + 2 + 1 or 0011 in binary
        int b = 6; // 4 + 2 + 0 or 0110 in binary
        int c = a | b;
        int d = a & b;
        int e = a ^ b;
        int f = (~a & b) | (a & ~b);
        int g = ~a & 0x0f;
        System.out.println("a = " + binary[a]);
        System.out.println("b = " + binary[b]);
        System.out.println("a|b = " + binary[c]);
        System.out.println("a&b = " + binary[d]);
        System.out.println("a^b = " + binary[e]);
        System.out.println("~a&b|a&~b = " + binary[f]);
        System.out.println("~a = " + binary[g]);
    }
}

Output:

a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100

Leave a Reply