IPA FE Subject B sample Question 6
A question IPA Japan published in 基本情報技術者試験 科目B サンプル問題 問6, translated into English. ITPEC is based on the same exams.
From the answer group below, select the correct answer to be inserted into blank in the program.
The function rev receives the 8-bit type argument byte, and returns the value with the order of its bits reversed. For example, when the function rev is called as rev(, the return value is 11010010.
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, value >> n performs a logical shift of the value of value by n bits to the right, and value << n performs a logical shift of the value of value by n bits to the left.
Answer group
Explanation
r ← (r << 1) ∨ (rbyte ∧ 00000001), then rbyte ← rbyte >> 1 — take the lowest bit of rbyte on each pass and push it into r from the right, so the bit taken first ends up leftmost.
rbyte ∧ 00000001 keeps only the lowest bit of rbyte. r << 1 moves the bits collected so far one place left, and ∨ puts the new bit into the freed lowest place. Then rbyte >> 1 brings the next bit down. After 8 passes the bit that was lowest in byte has moved left 7 times and is the highest: the order is reversed.
Trace of rev(, r after each pass: 00000001, 00000011, 00000110, 00001101, 00011010, 00110100, 01101001, 11010010, the expected return value.
Answer (a)
Why not others:
- •(b) —
rbyte >> 7keeps only the top bit ofrbyte, andr << 7throws away all but one collected bit:rgoes00000001,10000000, then00000000for good, sorev(returns01001011) 00000000 - •(c) —
(rbyte << 1) ∨ (rbyte >> 7)rotates the value one place left; eight rotations bring it back, sorev(returns01001011) 01001011unchanged - •(d) — the same with a rotation to the right: after eight passes the argument comes back unchanged
Key rule: To reverse bits, take them off one end (AND with 1, then shift right) and push them onto the other (shift left, then OR); a rotation only moves the bits round in the same order.
Math & Numbers · AI-written, may contain errors
This question comes from the past questions IPA Japan publishes, translated into English by ITPEC Practice. ITPEC Practice is an independent study tool and is not affiliated with IPA or ITPEC. See the original paper (PDF) or Report an issue.