ITPEC FE Subject B April 2025 Question 6

From the answer group below, select the correct combination of answers to be inserted into A and B in the program.

Gray code is a sequence of binary numbers in which two successive values differ by only 1 bit. The function GrayBiCon converts the gray code to a binary code using bitwise operators. The bitwise operators operate on the individual bits of the variables. The function receives the 8-bit type argument x as a gray code, and returns a corresponding binary number of the given argument. The value of each bit after conversion is the exclusive OR of the most significant bit in the gray code up to the corresponding bit position and the converted value of the next higher bit position. For instance, when the function GrayBiCon is called as GrayBiCon(00001100), the return value is a binary number 00001000. The common bitwise operators are listed in the table below:

Table Operators

OperatorName
&Bitwise AND
|Bitwise OR
^Bitwise XOR (exclusive OR)
<<Shift left
>>Shift right

For instance, v << n performs a logical shift of the value of v by n bits to the left.

[Program]
○ 8-bit: GrayBiCon(8-bit: x)
8-bit: y ← x
8-bit: z ← x
while (z ≠ 00000000)
z ← z A 1
y ← B
endwhile
return y

Answer group

OptionAB

Explanation

A: >>, B: y ^ z — XOR the code with each right-shifted copy of itself, so every bit becomes the XOR of all Gray bits from the MSB down to it.

The specification says each binary bit is the XOR of the Gray bits at and above its position. Shifting z right by 1, 2, 3, … brings each higher bit down under every lower position, and XOR-ing each shifted copy into y accumulates exactly those bits. The loop ends when every 1 bit has been shifted out of z.

Trace with x = 00001100:

Passzy
start0000110000001100
10000011000001010
20000001100001001
30000000100001000
40000000000001000

The function returns 00001000, the value in the example.

Answer (h)

Why not others:

  • •(a), (b) and (c) — z & 1 shifts nothing, it keeps only the lowest bit. For 00001100 it makes z zero at once, returning 00000000 (a) or the input unchanged (b) and (c); for an odd x, z stays 1 and the loop never ends.
  • •(d), (e) and (f) — << moves bits toward the MSB, so each bit is combined with the bits below it instead of above; (e) returns 00000100 for the example.
  • •(g) — AND only clears bits: the trace ends at 00000000.
  • •(i) — OR never clears a bit: the trace ends at 00001111.

Key rule: Gray to binary is a prefix XOR from the MSB (XOR the value with its right shifts until nothing is left); binary to Gray is the single step x ^ (x >> 1).

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.