retagged by
8,352 views
15 votes
15 votes

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

#include<stdio.h>
main(){
  unsigned int num;
  int i;
  scanf("%u", &num);
  for(i=0;i<16;i++){
    printf("%d", (num<<i&1<<15)?1:0);
  }
}
  1. It prints all even bits from num
  2. It prints all odd bits from num
  3. It prints binary equivalent of num
  4. None of above
retagged by

1 Answer

Best answer
15 votes
15 votes
#include <stdio.h>
int main() {
  unsigned short int num; // num is 16 bit unsigned integer
  int i;
  scanf("%u",&num);
  for(i=0;i<16;i++) {
    printf("%d",(num<<i & 1<<15)?1:0); 
    // ( (num<<i) & (1<<15) )?1:0
    // << has higher precedence than & 
  }
}
// num << i  == ith bit from MSB in the actual num is at the MSB position now
// 1 << 15 == 1000000000000000
// (num<<i)&(1<<15) check each bits of num starting from MSB and prints one by one  

Therefore: The program prints binary equivalent of num.


Above task can also be performed using the following program:

#include <stdio.h>
int main() {
  unsigned short int num;
  int i;
  scanf("%u",&num);
  for(i=15;i>=0;i--) 
    (num&(1<<i))?printf("1"):printf("0");
}
selected by
Answer:

Related questions

8 votes
8 votes
5 answers
1
sh!va asked May 7, 2017
8,625 views
What will be the output of the following C code?#include <stdio.h main() { int i; for(i=0;i<5;i++) { int i=10; printf("%d" , i); i++; } return 0; }10 11 12 13 1410 10 10 ...
5 votes
5 votes
2 answers
2
go_editor asked Jun 23, 2016
5,464 views
What is the output of the following C code?#include <stdio.h int main() { int index; for(index=1; index<=5; index++) { printf("%d", index); if (index==3) continue; } }124...
5 votes
5 votes
3 answers
3
sh!va asked May 7, 2017
7,088 views
We use malloc and calloc for:Dynamic memory allocationStatic memory allocationBoth dynamic memory allocation and static memory allocationNone of these
8 votes
8 votes
4 answers
4
sh!va asked May 7, 2017
5,459 views
What is the output of the following program?#include<stdio.h int tmp=20; main() { printf("%d", tmp); func(); printf("%d", tmp); } func() { static int tmp=10; printf("%d",...