PCEP Bitwise Operations 2 — Questions and Answers
Question 1: What is the result of `0b1010 & 0b1100` in Python?
- 0b1000 (Correct answer)
- 0b1110
- 0b0010
- 0b1010
Correct answer: 0b1000
AND keeps only bits that are 1 in both operands: 1010 & 1100 = 1000 (decimal 8).
Question 2: Which expression uses the bitwise OR operator in Python?
- x | y (Correct answer)
- x || y
- x or y
- x OR y
Correct answer: x | y
The single pipe `|` is Python's bitwise OR; `||` and `or` are logical operators.
Question 3: What does `~0` evaluate to in Python?
- -1 (Correct answer)
- 0
- 1
- 255
Correct answer: -1
The bitwise NOT of 0 flips all bits, giving -1 in Python's two's complement integers.
Question 4: What is `7 ^ 7` in Python?
- 0 (Correct answer)
- 7
- 14
- 49
Correct answer: 0
XOR of any value with itself always produces 0 because every bit cancels.
Question 5: What is the result of `1 << 4`?
- 16 (Correct answer)
- 4
- 8
- 32
Correct answer: 16
Left-shifting 1 by 4 positions is equivalent to 2^4 = 16.
Question 6: What does `32 >> 2` evaluate to?
- 8 (Correct answer)
- 4
- 16
- 128
Correct answer: 8
Right-shifting 32 by 2 positions divides by 4, giving 8.
Question 7: Which bitwise operator would you use to check whether the 3rd bit (value 4) of integer x is set?
- x & 4 (Correct answer)
- x | 4
- x ^ 4
- x >> 4
Correct answer: x & 4
ANDing with a mask isolates the target bit; a non-zero result means the bit is set.
What is the result of `0b1010 & 0b1100` in Python?