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(, the return value is a binary number 00001000. The common bitwise operators are listed in the table below:
Table Operators
For instance, v << n performs a logical shift of the value of v by n bits to the left.
Answer group
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:
The function returns 00001000, the value in the example.
Answer (h)
Why not others:
- •(a), (b) and (c) —
z & 1shifts nothing, it keeps only the lowest bit. For00001100it makeszzero at once, returning00000000(a) or the input unchanged (b) and (c); for an oddx,zstays 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) returns00000100for 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.