Bitwise operators in Java

# bit-wise

Know your primitive types

# AND(&)

if both bits are 1, it gives 1, else it gives 0.

    System.out.println(Integer.toBinaryString(6));          // 110
    System.out.println(Integer.toBinaryString(4));          // 100
    System.out.println(Integer.toBinaryString(6 & 4));      // 100
    System.out.println(6 & 4);                              // 4
1
2
3
4

# OR( | )

if either of the bits is 1, it gives 1, else it gives 0.

    System.out.println(Integer.toBinaryString(1));          // 01
    System.out.println(Integer.toBinaryString(2));          // 10
    System.out.println(Integer.toBinaryString(1 | 2));      // 11
    System.out.println(1 | 2);                              // 3
1
2
3
4

# Signed shift(>>)

Signed Right shift operator. Shifts the bits of the number to the right and fills the voids left with the sign bit

    System.out.println(Integer.toBinaryString(8));        // 1000
    System.out.println(Integer.toBinaryString(8 >> 1));   // 0100
    System.out.println(8 >> 1);                           // 4
1
2
3

# Unsigned shift(>>>)

Unsigned Right shift operator. Shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0. (>>>) is unsigned-shift; it’ll insert 0. (>>) is signed, and will extend the sign bit.

    System.out.println(Integer.toBinaryString(-16));          // 11111111111111111111111111110000
    System.out.println(Integer.toBinaryString(-16 >>> 2));    // 00111111111111111111111111111100
    System.out.println(-16 >>> 2);                            // 1073741820
1
2
3

# Signed shift(<<)

Shifts the bits of the number to the left and fills 0 on voids left as a result

    System.out.println(Integer.toBinaryString(1));          // 00000000001
    System.out.println(Integer.toBinaryString(1 << 10));    // 10000000000
    System.out.println(1 << 10);                            // 1024
1
2
3

# NOT(~)

all bits inverted

    System.out.println(Integer.toBinaryString(0));         // 00000000000000000000000000000000
    System.out.println(Integer.toBinaryString(~0));        // 11111111111111111111111111111111
1
2

# XOR(^)

if corresponding bits are different, it gives 1, else it gives 0.

    System.out.println(Integer.toBinaryString(9));         // 1001
    System.out.println(Integer.toBinaryString(11));        // 1011
    System.out.println(Integer.toBinaryString(9 ^ 11));    // 0010
    System.out.println(9 ^ 11);                            // 2
1
2
3
4