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

float calculate_entropy(FILE *file) {
    int byte_counts[256] = {0};
    int total_bytes = 0;
    float entropy = 0;

    int ch;
    while ((ch = fgetc(file)) != EOF) {
        byte_counts[ch]++;
        total_bytes++;
    }

    for (int i = 0; i < 256; i++) {
        if (byte_counts[i] > 0) {
            float probability = (float)byte_counts[i] / total_bytes;
            entropy -= probability * log2(probability);
        }
    }

    return entropy;
}

int main(int argc, char *argv[]) {
    if (argc > 1 && strcmp(argv[1], "-h") == 0) {
        printf("Usage: %s [filename]\n", argv[0]);
        return 1;
    }
    
    FILE *fp = argc > 1 ? fopen(argv[1], "rb") : stdin;
    if (fp == NULL) {
        perror("Error opening file");
        return 1;
    }

    float entropy = calculate_entropy(fp);
    fclose(fp);

    printf("Entropy: %f\n", entropy);
    return 0;
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: