What does the following program do when the input is unsigned 16-bit integer?…

2017

What does the following program do when the input is unsigned 16-bit integer?

C
#include 
main( )
{
unsigned int num;
int i;
scanf (“%u”, &num);
for ( i = 0; i<16; i++)
{
printf (“%d”, (num << i & 1 << 15 ) ? 1:0);
}
}


Answer: C. It prints binary equivalent of numThe program iterates 16 times, corresponding to the 16 bits of an unsigned integer. Inside the loop, it shifts 'num' left by 'i' positions and masks with '1…

  1. A.

    It prints all even bits from num

  2. B.

    It prints all odd bits from num

  3. C.

    It prints binary equivalent of num

  4. D.

    None of the above

Attempted by 476 students.

Show answer & explanation

Correct answer: C

The program iterates 16 times, corresponding to the 16 bits of an unsigned integer. Inside the loop, it shifts 'num' left by 'i' positions and masks with '1 << 15'. This extracts the bit at position (15 - i), starting from the most significant bit down to the least significant bit. The ternary operator prints 1 or 0 for each extracted bit. Consequently, the program outputs the binary representation of the input number.

Explore the full course: Iocl Engineers Officers Grade A Paper 2

Loading lesson…