3,760 views
12 12 votes

What is the following function doing?

unsigned int foo(unsigned int x)
{
    unsigned int c = sizeof x;
    c <<= 3;
    if(x == 0) return c;
    c--;
    while(x = x & x-1) c--;
        return c;   
}
  1. Counting the number of bits in the binary representation of x
  2. Counting the number of set bits in the binary representation of x
  3. Counting the number of unset bits in the binary representation of x
  4. None of the above

2 Answers

Best answer
14 14 votes
1. unsigned int foo(unsigned int x){
2.    unsigned int c = sizeof x;
3.    c <<= 3;
4.    if(x == 0) return c;
5.    c--;
6.    while(x = x & x-1) c--;
7.    return c;   
8. }

line no 2 : c = no of bytes for x.
line no 3 : c<<=3 is c*8 which is converting Byte into bits.
line no 6 : counting no of 1s and decrementing c value by 1.
c will be decremented as many times as no of 1s will be in x.
line no 7 : return c i.e. no of 0s or no of Unset bit in x.
• edited by
2 2 votes

Let's take a bad number, ie, not a power of 2. Let's take 53.

In binary, 53 = 110101. (4 ones, 2 zeroes)

    c <<= 3;

will give us the number of bits required to represent 53 in binary. See Digvijay Pandey's answer.

 

Now,

    while(x = x & x-1) c--;

When x is bitwise-ANDED with (x-1), it is a property that this result would contain one less 1 than x.

53 AND 52 = 110101 AND 110100 = 110100 (4 1's reduced to 3 1's)

110100 is 52. So,

52 AND 51 = 110100 AND 110011 = 110000 (3 1's reduced to 2 1's)

110000 is 48, So

48 AND 47 = 110000 AND 101111 = 100000 (2 1's reduced to 1 1)

100000 is 32, So

32 AND 31 = 100000 AND 011111 = 0 (1 1 reduced to 0 1's)

 

It took 4 steps. At each step we decremented c.

=> We decremented c four times.

=> From the bits required to represent 53, we subtracted 4 bits.

=> Number of bits remaining is the count of 0's in 53.

 

Option C

Answer:
Position:
Show:

Related questions

5 5 votes
3 answers 3 answers
4.6k
4.6k views
Arjun asked Oct 18, 2016
4,584 views
Consider the following C functions:int f1(int a, int b) { while (a != b) { if(a b) a = a - b; else b = b - a; } return a; } int f2(int a, int b) { while (b != 0) { int t...
6 6 votes
1 1 answer
3.3k
3.3k views
Arjun asked Oct 18, 2016
3,287 views
Consider the following incomplete C function for reversing a singly linked list.node* reverse(node* trav){ if(trav->next) __________________ else { head - next = null; he...
9 9 votes
2 answers 2 answers
2.4k
2.4k views
Arjun asked Oct 18, 2016
2,397 views
int foo(int n) { if(n 10000) return 1; int sum = 0, i; for( i = 0; i < n; i++) { sum += i; } return sum; }The value returned by the above function is$\Theta\left(n^2\rig...
8 8 votes
1 answers 1 answer
3.2k
3.2k views
Arjun asked Oct 18, 2016
3,189 views
int foo1(float a) { int b = a; return b/2; } int foo2(double a) { int b = a; return b/2; } int foo3(unsigned int a) { int b = a; return b/2; }Consider the above three C f...