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

Discussion

Assuming a integer 2-bytes, What will be the output of the program?

#include <stdio.h>

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

 

  • A.ffff
  • B.fff8
  • C.0 
  • D.-1

Answer: B

Correct answer: fff8

On a 2-byte int, \( -1 \) is all ones: 0xffff. Shifting left by three discards the top three bits and brings three zeros in at the bottom:

\[ 1111\,1111\,1111\,1111_2 \ll 3 = 1111\,1111\,1111\,1000_2 = \mathtt{0xfff8} \]

The quick check is that the low three bits become zero and nothing else changes, so only the last hex digit moves, from f to 8. Note that left-shifting a negative value is undefined behaviour in C; the result shown is what implementations produce, not what the standard guarantees.

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

Post your comment

Please log in or register to post a comment.