Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count the zeros and ones in a file?

Tags:

c++

binary

Given a file (binary or textual), what is the fastest or most elegant way in C++ to count the ones and zeros in the binary representation of that file?

like image 858
Andrew Buss Avatar asked Oct 10 '10 23:10

Andrew Buss


People also ask

How do you count the number of zeros in a list?

Python List Count Zero / Non-Zero. To count the number of zeros in a given list, use the list. count(0) method call.

How do you count zeros in C++?

Count numbers having 0 as a digit in C++If any digit is found as zero increment count and move to next number otherwise reduce the number by 10 to check digits until number is >0. Let's understand with examples. Starting from i=10 to i<=11 Only 10 has 0 as a digit. No need to check the range [1,9].


2 Answers

I would recommend you use results array:

unsigned char cheating[] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3,
        4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2,
        3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4,
        5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2,
        3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4,
        5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5,
        6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3,
        4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3,
        4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6,
        7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4,
        5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5,
        6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };

After you read the file in as unsigned char array you can just sum:

    for (int i = 0; i < arraysize; i++) {
        sum0+=8-cheating[unsignedbytearray[i]];
        sum1+=cheating[unsignedbytearray[i]];
    }

It is very hard to write code, that would be faster or more elegant :P

like image 102
Margus Avatar answered Oct 02 '22 23:10

Margus


Create a 256 length char array. Stream through the file a byte at a time incrementing the array position of each byte. Hard code the number of 1s in each of the 256 bytes in another array. Multiply the 2 arrays and sum.

Not sure about elegance and definitely requires more memory, but might be faster than linuxuser27's algorithm.

like image 37
aepryus Avatar answered Oct 02 '22 23:10

aepryus