Assuming int is 2 bytes, what is printed by this C program (two’s complement typical behavior)? #include<stdio.h> int main() { printf("%x ", -2 << 2); return 0; }

Difficulty: Medium

Correct Answer: fff8

Explanation:


Introduction / Context:
This question explores bit shifting and formatting in C under the common two’s complement representation, with the added assumption that int is 16 bits (2 bytes). Although left-shifting negative values is technically undefined by the standard, many legacy questions expect the conventional two’s complement interpretation.


Given Data / Assumptions:

  • Assume int is 16 bits.
  • Two’s complement representation for negative numbers.
  • printf with "%x" prints the value as an unsigned hexadecimal form of the passed int.


Concept / Approach:
Under typical two’s complement behavior, -2 is represented as 0xFFFE in 16 bits. A left shift by 2 multiplies by 4, so -2 << 2 becomes -8. Interpreting -8 as an unsigned 16-bit pattern yields 0xFFF8, which prints as fff8 in lowercase hex.


Step-by-Step Solution:
Represent -2 in 16-bit two’s complement: 0xFFFE.Shift left by 2 bits: 0xFFFE << 2 → 0xFFF8 (low bits discarded).As a signed value, this is -8; when formatted with %x, the hex digits of the two’s complement pattern are printed → fff8.


Verification / Alternative check:
Manually compute using binary: -2 = 1111 1111 1111 1110; shift left two → 1111 1111 1111 1000 = 0xFFF8.


Why Other Options Are Wrong:
(a) ffff corresponds to -1, not -8. (b) 0 would require the shifted value to be zero, which it is not. (d) The code compiles; the run-time value is implementation-defined but commonly prints fff8 under the stated assumptions. (e) 0008 would be +8, not -8.


Common Pitfalls:
Confusing language standard undefined behavior with typical hardware behavior; for exam settings with explicit assumptions, follow the intended model.


Final Answer:
fff8

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion