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(11001011), 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.

[Program]
○ integer: count1(bit8: byte)
bit8: rbyte ← byte
integer: r ← 0
integer: i
for (increase i from 1 to 8 by 1)
if ((blank) ≠ 00000000)
r ← r + 1
endif
endfor
return r

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 mask 00000001 << (i - 1) is 00000001, 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 of rbyte is 1, and r counts 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) — << i tests bits 1 to 7 and, at i = 8, shifts the 1 out entirely; bit 0 is never tested, so 11001011 gives 4
  • •(c) — << (i + 1) tests only bits 2 to 7, so 11001011 gives 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 returns rbyte), so 11001011 gives 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.