Logical shift right by 3 operation on signed integer -28. What's the correct answer?
- +203
- +83
- +3
- -3
2's complement of -28 is 11100100. Now if I apply logical right shift operation I am not getting any one of above answers.
Logical shift right by 3 operation on signed integer -28. What's the correct answer?
2's complement of -28 is 11100100. Now if I apply logical right shift operation I am not getting any one of above answers.
I'm almost certain it's a trick question.
The interviewer was seeing if you would answer "-3". If you would have (with the faulty reasoning that since 28>>>3 is 3 then -28>>>3 is -3), he would have realized that you don't understand two's complement.
He wanted you to answer that none of the four choices is correct. He wanted you to
Maybe the trick is not to assume two's complement representation. Assuming sign-and-magnitude representation, the answer can be -3, since most shifting implementations would not involve the sign bit.
It's a stupid question as:
Some languages (like Java I believe) the new most-significant bits such that any platform that doesn't have a suitable CPU instruction will have to issue several to calculate the required answer, whereas other languages may make an implementation-defined choise between the behaviours the CPU natively offers.
2's complement is the most common representation of negative numbers. Your question states "2's complement of -28 is 11100100."... I'm guessing that wasn't provided as part of the question (a bit weird if so, as it's after the answers). Still...
If we run with 2's complement...
11100100 >> 3 = 00011100 or 11111100 = 28 or -4
If the representation was 1's complement:
11100011 >> 3 = 00011100 or 11111100 = 28 or -3
If the representation was sign-bit, absolute-value:
10011100 >> 3 = 00010011 or 11110011 = 19 or -(127-12)=-115
(note that the question says a logical bit shift, which by definition ignores any possible interpretation of the bits, so the sign bit is shifted along with others)
Re #bits in an int... I think it's so obvious that that would either result in a value that's too large to match any of the options, or else it wouldn't make any difference (if 1s are being added at left for a 1's or 2's complement), that we can ignore that issue.
So, unless my quick calculation above slipped up, -3 is the only answer that could be correct on any plausible architecture, but is still very unlikely. All up, I'm wondering if they weren't actually testing to see who had the confidence to leave the question unanswered, or annotate that none of the answers were likely correct....