Hi,
I need to count number of ones and zeros in the following binary number: 11000111101011101100011100011011.
Issue: It is correctly counting number of ones uptill 17 bits i-e 11000111101011101 . But when i increase my binary number it gives false answer.
Try: I have already use the "long long int" but no use.
below is the C code which i tried .

#include<stdio.h>
int main()
{

  int r, ones=0, zeroes=0;
  long int n;
  printf("Enter a Binary Number ");
  fflush( stdout ); 
  scanf("%ld", &n); 
  while(n!=0)
  {
    r=n%10;
    if(r==1)
      ones++;
    if(r==0)
      zeroes++;
    n=n/10;
  }
  printf("\nNumber of ones are %d", ones);

  getchar(); 
  return 0;
}

I see a few problems.

  1. %ld is for long integers. If you answer 11000111101011101100011100011011 to line 9, most C compilers would be capable of containing at least the [−2,147,483,647, +2,147,483,647] so you would blow past this data type capacity.
  2. To overcome such a limitation consider using strings. Then you could find the string's length and use it to count 0's and 1's. Psuedo code only!

strcopy(inputstring, otherstring);
Remove all the 0's with https://www.daniweb.com/programming/software-development/threads/190592/remove-characters-from-string-c from otherstring.
zeros = strlen(inputstring) - strlen(otherstring);

Now you are not limited to long int.

For future reference, if you want to count bits in an integer you should make it an unsigned int, and use bitwise shift right operations rather than division.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.