/* entropy.c - Entropy calculator - Don Yang (uguu.org) 02/17/03 */ #include #include #include #include #define BUFSIZE 4096 int main(int argc, char **argv) { static unsigned char buffer[BUFSIZE]; static unsigned int freq[256]; double p, entropy, log2; FILE *infile; size_t i, size, filesize; int a; if( argc < 2 ) return printf("%s [...]\n", *argv); log2 = log(2); for(a = 1; a < argc; a++) { printf("%s: ", argv[a]); if( (infile = fopen(argv[a], "rb")) == NULL ) { (void)puts("fopen() failed"); continue; } memset(freq, 0, 256 * sizeof(int)); filesize = 0; while( feof(infile) == 0 ) { if( (size = fread(buffer, 1, BUFSIZE, infile)) == 0 ) break; if( size > BUFSIZE ) break; for(i = 0; i < size; freq[(unsigned int)(buffer[i++])]++); filesize += size; } (void)fclose(infile); entropy = 0.0; for(i = 0; i < 256; i++) { if( freq[i] > 0 ) { p = (double)(freq[i]) / (double)filesize; entropy -= p * log(p) / log2; } } printf("%g bits\n", entropy); } return 0; }