ITPEC FE Subject B April 2024 Question 6
From the answer group below, select the correct answer to be inserted into blank in the program.
The function count1 receives the bit8 type (8-bit type) argument byte, and returns the number of bits 1 in the argument. For example, when the function count1 is called as count1(, the return value is 5.
Here, operator & represents a bitwise logical product, operator | represents a bitwise logical sum; operator >> represents a logical shift to the right, and operator << represents a logical shift to the left. For example, v << n performs a logical shift of the value of v by n bits to the left.
Answer group
Explanation
rbyte & (00000001 << (i - 1)) — shift a single 1 to bit position i - 1 and AND it with the byte, testing one bit per pass.
- •For
i= 1 to 8 the mask00000001 << (i - 1)is00000001,00000010, …,10000000: each of the 8 bits exactly once. - •
&keeps only the bit under the mask, so the result is non-zero exactly when that bit ofrbyteis 1, andrcounts it.
Trace for 11001011: the masks for i = 1, 2, 4, 7 and 8 find a 1 (bits 0, 1, 3, 6 and 7), while i = 3, 5 and 6 give 00000000. The function returns 5, as the question states.
Answer (a)
Why not others:
- •(b) —
<< itests bits 1 to 7 and, ati= 8, shifts the 1 out entirely; bit 0 is never tested, so11001011gives 4 - •(c) —
<< (i + 1)tests only bits 2 to 7, so11001011gives 3 - •(d), (e) and (f) —
|sets the mask bit instead of testing it; the result is non-zero on every pass (a mask shifted out to zero just returnsrbyte), so11001011gives 8
Key rule: To test one bit, AND with a mask that has a single 1 in that position, shifting by 0 up to width − 1; OR is for setting bits, not testing them.
Math & Numbers · AI-written, may contain errors
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.