ProgrammingHardProduct company OA

Assume 16-bit unsigned short and 32-bit int. What is printed?

Assume 16-bit unsigned short and 32-bit int. What is printed?
unsigned short v = 0x1234;
unsigned short w = (unsigned short)(v << 8 | v >> 8);
printf("%04X", w);
  1. A. 3412
  2. B. 123412
  3. C. 1234
  4. D. 3400

Correct answer: A. 3412

v is promoted to int, so v << 8 = 0x123400 and v >> 8 = 0x12; OR gives 0x123412. Casting back to 16 bits keeps the low half, 0x3412: the two bytes are swapped. Without the cast you would see the 0x12 hanging on top.

More C Programming questions

Exams that ask this topic