Previous | Home | Next |
While working with any kinds of the integer types, we have the bitwise operators that can directly work with the bits that make up the integers, i.e. you can use masking techniques to get at individual bits in a number. Following are the basic bitwise operators that are commonly used :
-
& (AND) Bitwise operator : A bitwise AND operation takes two binay representations of same length and then performs the logical AND operation on the bits of the binary numbers. If 1is logically ANDed with 1 the result is 1, else the result is 0. For e.g.
0 0 1 0
1 0 1 1
AND 0 0 1 0
-
~ (NOT) Bitwise operator: A NOT Bitwise operator is a unary operation that perform logical negation on each bit. i.e it performs a one's complement on the binary representation of the integers. The digits with 0 becomes 1 and vice-versa. For e.g.
0 0 1 1
NOT= 1 1 0 0
-
|(OR ) Bitwise operator: A bitwise OR operation takes two binary representations of same length and then performs logical OR operation on bits of the binary numbers. If 1 is logically OR with 1 or 0 the result is 1 and if 0 is OR with 0 the result is zero. For eg.
0 1 1 0
1 0 1 1
OR = 1 1 1 1
-
^ (XOR) Bitwise operator: A bitwise XOR operation takes two binary representation of same length and then performs logical XOR operation on bits of the binary numbers. The result is 1 if both the binary digits are different else result is 0. For e.g.
0 0 1 1
1 0 0 1
XOR=1 0 1 0
The order of preceedence for the bitwise operators starting with the highest preceedence first is given by | > ^ > &.
There are also >> and << operators, which shift a bit pattern to the right or left. These operators are often convenient when you need to build up bit patterns to do bit masking.
int fourth_from_right = (p & (1 << 3)) >> 3;
There is even a >>> operator that fills the top bits with zero, whereas >> extends the sign bit into the top bits. There is no >>> operator.
Previous | Home | Next |