Explore the functionality and effects of shift operators with these medium-level questions, focusing on left and right bit-shift operations and their outcomes. Enhance your familiarity with binary manipulation and practice your understanding of how shift operators work in code.
What is the result of performing a left shift (u003Cu003C) by 2 on the binary number 0001 (decimal value 1)?
Explanation: Shifting 0001 left by 2 positions adds two zeros to the right, resulting in 0100, which is decimal 4. 0010 (decimal 2) would be the result of a single left shift, not two. 1000 (decimal 8) comes from left-shifting by three places. 0000 (decimal 0) would only occur if all bits were shifted out. Only the first option correctly reflects a two-place left shift.
When a signed 8-bit integer with binary value 11111100 (decimal -4) is right-shifted by 1 using the arithmetic shift operator (u003Eu003E), what is the resulting value?
Explanation: An arithmetic right shift preserves the sign bit, so shifting 11111100 right by one yields 11111110, which is -2 in 8-bit two's complement. 01111110 would be the outcome if the sign bit were not preserved, but that's not how arithmetic shift works. 11111000 represents -8 and results from other operations. 00000010 is positive 2, which is not possible when shifting a negative number arithmetically right.
How can you clear (set to 0) the least significant bit of any integer value 'n' using shift operators?
Explanation: Right shifting by 1 removes the least significant bit, and left shifting by 1 restores the original bit positions with 0 in the least significant place. The first option reverses the intended effect. Shifting only left or only right by two positions does not specifically clear just the least significant bit. The correct method isolates this operation as described in the correct answer.
What is the value resulting from unsigned right-shifting the 8-bit binary number 10000000 (decimal 128) by 3 positions?
Explanation: Unsigned right-shifting 10000000 (128) by three positions moves the single set bit three places to the right, producing 00010000, which is decimal 16. 10010000 (144) results from a left shift and setting another bit. 00001000 (8) would be the outcome of a four-position shift. 00000010 (2) does not correspond to a three-position shift from the original value.
Which statement correctly uses shift operators to determine if an integer is odd?
Explanation: Removing and restoring the least significant bit with (n u003Eu003E 1) u003Cu003C 1 will return the same number for even values, but differ by one for odd numbers. The second statement is incorrect since left shifting always changes the value unless n is zero. The third option only holds for n equal to 1, not for all odd numbers. The fourth statement is true for any positive n but does not determine oddness.