- Bitwise operators are used to performing manipulation of individual bits of a number.
- They can be used with any of the integral types (char, short, int, etc).
- They are used when performing update and query operations of Binary indexed tree.
Bitwise OR ( | )
- This operator is a binary operator, denoted by ‘|’.
- It returns bit by bit OR of input values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise OR Operation of 5 and 7 0101 | 0111 ________ 0111 = 7 (In decimal)
public class BitwiseOr { public static void main(String[] args) { int x = 5; int y = 7; System.out.println(x|y); //7 } }
Bitwise AND ( & )
- This operator is a binary operator, denoted by ‘&’.
- It returns bit by bit AND of input values, i.e, if both bits are 1, it gives 1, else it gives 0.
a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise AND Operation of 5 and 7 0101 & 0111 ________ 0101 = 5 (In decimal)
public class BitwiseAnd { public static void main(String[] args) { int x = 5; int y = 7; System.out.println(x&y); //5 } }
Bitwise XOR (^) –
- This operator is a binary operator, denoted by ‘^’.
- It returns bit by bit XOR of input values, i.e, if corresponding bits are different, it gives 1, else it gives 0.
a = 5 = 0101 (In Binary) b = 7 = 0111 (In Binary) Bitwise XOR Operation of 5 and 7 0101 ^ 0111 ________ 0010 = 2 (In decimal)
public class BitwiseXor { public static void main(String[] args) { int x = 5; int y = 7; System.out.println(x^y); //2 } }
Bitwise Complement (~) –
- This operator is a unary operator, denoted by ‘~’.
- It returns the one’s complement representation of the input value, i.e, with all bits inverted, means it makes every 0 to 1, and every 1 to 0.
a = 5 = 0101 (In Binary) Bitwise Compliment Operation of 5 ~ 0101 ________ 1010 = 10 (In decimal)