Bitwise Operators
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.
- The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, 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 "00000000" would change its pattern to "11111111".
- 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 unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
- The bitwise & operator performs a bitwise AND operation.
- The bitwise ^ operator performs a bitwise exclusive OR operation.
- The bitwise | operator performs a bitwise inclusive OR operation.
Java Bitwise Operators Example
public class BitwiseManipulation {
public static void main(String args[]) {
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
System.out.println("a & b = " + c);
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c);
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c);
c = ~a; /*-61 = 1100 0011 */
System.out.println("~a = " + c);
c = a << 2; /* 240 = 1111 0000 */
System.out.println("a << 2 = " + c);
c = a >> 2; /* 215 = 1111 */
System.out.println("a >> 2 = " + c);
c = a >>> 2; /* 215 = 0000 1111 */
System.out.println("a >>> 2 = " + c);
}
}
Count the number of bits set in an integer
public class CountBit {
public static void main(String[] args) {
int count = 0;
int value = 7;
while (value > 0) {
if ((value & 1) == 1) {
count++;
}
value >>= 1;
}
System.out.println("Number of 1s: " + count);
}
}
References
Bitwise and Bit Shift Operators in Oracle DocsJava Bitwise Operators Example in Tutorials Point
No comments:
Post a Comment