PCEP Bitwise Operations 3 — Questions and Answers
Question 1: What is the decimal value of `0b0101 | 0b1010`?
- 15 (Correct answer)
- 0
- 5
- 10
Correct answer: 15
0101 | 1010 = 1111 in binary, which equals 15 in decimal.
Question 2: What is `~5` in Python?
- -6 (Correct answer)
- -5
- 5
- 6
Correct answer: -6
~n = -(n+1), so ~5 = -6.
Question 3: What is the result of `0xFF & 0x0F`?
- 0x0F (Correct answer)
- 0xFF
- 0xF0
- 0x00
Correct answer: 0x0F
0xFF & 0x0F keeps only the lower nibble: 0x0F (decimal 15).
Question 4: How would you set bit 2 (value 4) of variable `x` without changing other bits?
- x = x | 4 (Correct answer)
- x = x & 4
- x = x ^ 4
- x = x >> 4
Correct answer: x = x | 4
OR with a mask sets the target bit to 1 while leaving all other bits unchanged.
Question 5: What is `3 ^ 5` in Python?
- 6 (Correct answer)
- 2
- 8
- 15
Correct answer: 6
3 = 011, 5 = 101; XOR gives 110 = 6.
Question 6: Which operation clears (sets to 0) bit 1 (value 2) of variable `x`?
- x = x & ~2 (Correct answer)
- x = x | 2
- x = x ^ 2
- x = x >> 2
Correct answer: x = x & ~2
ANDing with the complement of the mask (~2) forces the target bit to 0.
Question 7: What is the output of `print(bin(10 >> 1))`?
- 0b101 (Correct answer)
- 0b1010
- 0b10100
- 0b100
Correct answer: 0b101
10 in binary is 1010; shifting right by 1 gives 0101, which is 5, printed as 0b101.
What is the decimal value of `0b0101 | 0b1010`?