Machine-translated by Google. Questions are authored in English.
Top

Discussion

Assunming, integer is 2 byte, What will be the output of the program?

#include <stdio.h>

int main()
{
    printf("%x\n", -1>>1);
    return 0;
}

 

  • A.ffff
  • B.0fff
  • C.0000
  • D.fff0

Answer: A

Correct answer: ffff

\( -1 \) in two's complement is all ones, so on a 2-byte int it is 0xffff.

Right-shifting a signed negative value is implementation-defined, and every common compiler performs an arithmetic shift, propagating the sign bit into the vacated position. All ones shifted right with ones coming in is still all ones, so the result is unchanged at 0xffff, which %x prints as ffff.

Had the shift been logical, a zero would have entered at the top and the answer would have been 7fff. That difference is exactly why shifting negative values is best avoided in portable code.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.