Commentary below slide.
|
|
Slide 33 of 95
Notes:
AND-ing bits is similar to the logical AND just discussed. We assign the bit value 1 to be true and the bit value 0 to be false. Therefore, the AND of two bits is 1 only if both bits are 1; otherwise it is 0.
The bitwise AND operator (&) takes two parameters, one on each side of the operator. This operator returns an int value that is the result of AND-ing each bit in each position of the first parameter with the bit in the corresponding position in the other parameter.
In the example above, num1 and num2 are int values, even though only the last 4 bits are shown. num1 has the value 3 and its corresponding bit pattern for bit positions 0 through 3 is 0011. num2 has the value 6 and its corresponding bit pattern for bit positions 0 through 3 is 0110. The expression num1 & num2 results in an int whose bit in the 0th position is the AND of the bit in num1’s 0th bit position and the bit in num2’s 0th bit position, and whose bit in the 1st position is the AND of the bit in num1’s 1st bit position and the bit in num2’s 1st bit position, and so on. The bit in num1’s 0th bit position is 1 and the bit in num2’s 0th bit position is 0; the AND of these is 0. So the 0th bit position for the return value is 0. The bit in num1’s 1st bit position is 1 and the bit in num2’s 1st bit position is 1; the AND of these is 1. So the 1st bit position for the return value is 1. The bit in num1’s 2nd bit position is 0 and the bit in num2’s 2nd bit position is 1; the AND of these is 0. So the 2nd bit position for the return value is 0. The bit in num1’s 3rd bit position is 0 and the bit in num2’s 3rd bit position is 0; the AND of these is 0. So the 3rd bit position for the return value is 0. Putting together, the bit pattern for the return value is 0010 which is 2 decimal.