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;
}

Dani AI

Generated

Quick diagnosis: the problem is not your loop logic but the input type. Reading the binary as a decimal integer (with scanf into long/long long) will overflow once the numeric value grows beyond the platform type, and any leading zeros are lost. As suggested, treat the input as text when you need to count digits. If the input truly represents a machine integer that fits in 32/64 bits, ’s unsigned/bitwise approach is appropriate — but for arbitrary-length binary strings the safe, simple option is to count characters in a string.

A robust string-based approach (preserves leading zeros, no overflow, validates characters):

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[1024];
    if (!fgets(buf, sizeof buf, stdin)) return 0;
    size_t len = strlen(buf);
    if (len && buf[len-1] == '\n') buf[--len] = '\0';
    int ones = 0, zeros = 0;
    for (size_t i = 0; i < len; ++i) {
        if (buf[i] == '1') ++ones;
        else if (buf[i] == '0') ++zeros;
        else { fprintf(stderr, "invalid character '%c' at position %zu\n", buf[i], i); return 1; }
    }
    printf("ones=%d zeros=%d\n", ones, zeros);
    return 0;
}

If the binary string is known to be <= 64 bits and you want a fast bit-count, convert with strtoull(..., 2) and use a popcount (GCC/Clang: __builtin_popcountll, or use Kernighan’s loop while(x){x &= x-1; ++c;}). Always check errno/endptr for overflow and reject strings longer than 64 bits.

Quick troubleshooting tips: use fgets (not scanf("%ld")) to avoid overflow and preserve leading zeros; trim newline before counting; validate characters; for extremely large inputs stream and count char-by-char (e.g., int ch = getchar() loop) to avoid storing the whole string. This addresses the overflow you saw with the longer binary literal posted by and implements the string/bitwise options mentioned by and .

Recommended Answers

All 2 Replies

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.