# Thread: Bitcount code

1. ## Bitcount code

Hello,

I am trting to write a program that accepts numbers and count the number of bits in the given array of numbers. However my output is incorrect, I get the following

Enter nums:
10101010
The total count is 7

Code:
```//Program that accepts a number and counts the bits.

#include <stdio.h>

int bitcnt(unsigned x);

int main (int argc, char *argv[]) {
unsigned x;

printf("Enter nums:\n");
scanf("%d", &x);
//    bitcnt(x);

printf("The total count is %d\n", bitcnt(x));

return 0;
}

int bitcnt(unsigned x) {
int b;

for(b=0; b<x; x>>=1) {
if(x&01) {
b++;
}
}
//   printf("The total count is %d\n", b);
return b;
}```
All help is greatly appreciated.

2. Code:
```int bitcnt(unsigned x) {
int b;

for(b=0; x; x>>=1) {
if(x&1) {
b++;
}
}
//   printf("The total count is %d\n", b);
return b;
}```

3. Ah ha ...

That makes sense now. Thanks alot for that.

Also is this the correct output?

Enter nums:
1001
The total count is 7

Thank You

4. Well, no - clearly there are 8 bits in a byte.

Counting like a C programmer, are you?

5. Well....Thanks for that

I dont quite understand why it is giving me that output and what i should do to modify it.

Thank You

Also i am new to programming, so my knowledge is a bit limited about C language.

6. Code:
```    printf("Enter nums:\n");
bitcnt += scanf("%d", &x);

// OR

printf("Enter nums:\n");
scanf("%d", &x);
++bitcnt;```

7. 1001 is 1111101001 in binary, so it has 7 1-bits in it and the answer is correct. Now you have to figure out if you've asked the correct question.

If you want to treat your input as a binary value, look into reading it as a string and then counting the number of 1s in that string.

If you want figure out how many bits in total, look at the sizeof() operator combined with the CHAR_BIT value defined in limits.h.

Popular pages Recent additions