Skip to content

Instantly share code, notes, and snippets.

@bradley219
Created November 1, 2016 09:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradley219/1a822c4bde96cf5271fbf47a518544f4 to your computer and use it in GitHub Desktop.
Save bradley219/1a822c4bde96cf5271fbf47a518544f4 to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdio.h>
int ones_count(uint32_t i) {
    i = i - ((i >> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
    return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
int main (int argc, char *argv[]) {
    const char *filename = argv[1];
    FILE *fp = fopen(filename, "r");
   
    if ((fp = fopen(filename, "r" )) == NULL) {
        perror("error opening file");
        return 1;
    }
    long total = 0;
    long total_ones = 0;
    long total_zeros = 0;
    long l = 0;
    while (!feof(fp)) {
        uint32_t buffer;
        int count = fread(&buffer, 1, 4, fp);
        if (ferror(fp)) {
            perror("read error");
            break;
        }
        total += count;
        if (count == 4) {
            int ones = ones_count(buffer);
            int zeros = 32 - ones;
            total_ones += ones;
            total_zeros += zeros;
        }
        if (!(l % (1024 * 1024))) {
            printf("read %ld mb\n", total / 1024 / 1024);
            printf("total ones: %ld\n", total_ones);
            printf("total zeros: %ld\n", total_zeros);
            printf("1/0: %f\n", (double)total_ones / (double)total_zeros);
            printf("\n");
        }
        l++;
    }
    printf("read %ld bytes\n", total);
    printf("total ones: %ld\n", total_ones);
    printf("total zeros: %ld\n", total_zeros);
    printf("1/0: %f\n", (double)total_ones / (double)total_zeros);
    fclose(fp);
    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment