I am trying to count the no of zeroes and ones from a binary file. The problem is, I am getting correct no. of zeroes but ones are coming out to be equal to no. of zeroes. What I am doing is reading the file char by char . Since there can be max 256 chars I am storing the results in a temporary array for both zeroes and ones, and retrieve from there if a character occurs again.
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
void func(int* a1 ,int* a2)
{
for(int i=0;i<256;i++)
for(int j=0;j<8;j++)
{
if( (i & 1) ==1 )
{
a1[i]+=1;
}
else if( (i & 1) ==0 )
{
a2[i]+=1;
}
i>>1;
}
}
int main()
{
int zero[256];
int one[256];
int tzero[256];
int tone[256];
for(int i=0;i<256;i++)
{
zero[i]=0;
one[i]=0;
tzero[i]=0;
tone[i]=0;
}
func(tone,tzero);
FILE* input;
FILE* output;
output=fopen("ascii.txt","w");
input=fopen("one.bin","r");
int c;
while((c=fgetc(input))!=EOF)
{
fprintf(output,"%d\n",c);
zero[c]+=tzero[c];
one[c]+=tone[c];
}
int zeroes=0;
int ones=0;
for(int i=0;i<=255;i++)
{
zeroes+=zero[i];
ones+=one[i];
}
cout<<"zeroes:"<<zeroes<<endl;
cout<<"ones:"<<ones<<endl;
fclose(input);
fclose(output);
}
The loop that counts zeros and ones destroys the value of c by doing
c >>= 1;
After all eight shifts are complete, c is always zero, so the following code increments wrong counts:
// The value of c is always zero
tzero[c]=z;
tone[c]=o;
one[c]+=tzero[c];
zero[c]+=tzero[c];
You should save the value of c before the bit-counting loop, and restore it after the loop is over.
Better yet, compute the values of tzero[] and tone[] upfront, without waiting for them to occur in the file. This would make the body of your main loop very short and clean:
while((c=fgetc(input))!=EOF) {
one[c] += tzero[c];
zero[c] += tzero[c];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With