ITPEC FE Subject B April 2024 Question 6
ITPEC FE Subject B April 2024 — Question 6 of 20
Filling in missing bitwise logic to count the number of set bits (1s) in an 8-bit value.
The function count1 counts how many bits are 1 in an 8-bit input (popcount). It loops i from 1 to 8 and checks each bit using a bitmask.
The correct expression is:
rbyte & (00000001 << (i - 1))
How it works step by step:
- •
00000001 << (i - 1)creates a mask with a single1at bit positioni - 1 - •
i = 1→ mask =00000001(bit 0) - •
i = 2→ mask =00000010(bit 1) - •...
- •
i = 8→ mask =10000000(bit 7) - •
rbyte & maskisolates that one bit using bitwise AND - •If the result
≠ 00000000, the bit is1, so the counterrincrements
Verification with example: count1(11001011) should return 5.
- i=1: 11001011 & 00000001 = 00000001 ≠ 0 → r=1
- i=2: 11001011 & 00000010 = 00000010 ≠ 0 → r=2
- i=3: 11001011 & 00000100 = 00000000 = 0 → skip
- i=4: 11001011 & 00001000 = 00001000 ≠ 0 → r=3
- i=5: 11001011 & 00010000 = 00000000 = 0 → skip
- i=6: 11001011 & 00100000 = 00000000 = 0 → skip
- i=7: 11001011 & 01000000 = 01000000 ≠ 0 → r=4
- i=8: 11001011 & 10000000 = 10000000 ≠ 0 → r=5 ✓
Why not others:
- (b) `<< i` — shifts 1 to 8 positions, skipping bit 0 and going out of range at i = 8
- (c) `<< (i + 1)` — shifts 2 to 9 positions, missing even more bits
- (d), (e), (f) use `|` (OR) — OR does not isolate a bit; it sets the bit, so the result is almost always non-zero regardless of the original value
Key rule: to test whether a specific bit is set, use AND (&) with a bitmask — never OR (|).
AI-generated — may contain errors
The original exam layout is preserved in the image so diagrams, formulas, tables, and code remain accurate.
This question comes from an official ITPEC past paper. ITPEC Practice is an independent study tool and is not affiliated with ITPEC. See the official FE past-paper collection or Report an issue.