retagged by
490 views
2 votes
2 votes
#include <stdio.h>
int foo(unsigned word) {
	int n = 0;
	int num_set_bits[16] = {0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
	while( word > 0 ) {
		n += num_set_bits[ word & 0xF ];
		word >>= 4;
	}
	return n;
}
int main() {
	printf("%d\n",foo(0xABC));
	return 0;
}

Output of the above program ?

retagged by

1 Answer

1 votes
1 votes

In this code good use of bit manipulation and shift operation is done..Let us se iteration by iteration..

In 1st iteration , 

Word  =  0x ABC meaning in hexadecimal notation

n = 0 initially 

Now the operation  word & 0xF will do bitwise OR operation with the current value of word which is ABC as of now..

So 0xF can also be written by 0x 00F as we can always 0 on left before decimal point without loss of any value ..So

ABC  AND  00F  will yield  C only..So index of num_set_bits  =  C  =  12

Hence num_set_bits[12] = 2 , so n = n + 2   =  2

And word is right shifted 4 times which is equivalent to division by 16 or in other words shifting right by one hexadecimal digit..

So word  =  AB now

In 2nd iteration :

AB AND 0F  =  B

So n = n + num_set_bits[11]

        = 2 + 3  =  5

And word  = AB >> 4  =  A

In 3rd iteration :

A   AND  F   =    A

So  n  =  n + num_set_bits [10]

          =  5  +  2

          =  7

Hence the final answer is 7 ..

Related questions

0 votes
0 votes
1 answer
1
Psnjit asked Jan 12, 2019
1,137 views
main(){unsigned int i= 255;char *p= &i;int j= *p;printf("%d\n", j);unsigned int k= *p;printf("%d", k);} Both the outputs are -1. I have even tried with - int i = 255(3rd ...
0 votes
0 votes
1 answer
2
Mr khan 3 asked Nov 3, 2018
978 views
#include<stdio.h void fun(int *p,int *q) { p=q; *p=q; } int i=0,j=1; int main() { fun(&i,&j); printf("%d%d",i,j); }What will be the output of i and j in 16-bit C Compiler...
0 votes
0 votes
0 answers
4
garvit_vijai asked Sep 2, 2018
683 views
Please explain the output for the following program: #include<stdio.h>int main() { int i = 100; int *a = &i; float *f = (float *)a; (*f)++; pri...