Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2014
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <string.h>
  5.  
  6. #define SIZE 256
  7.  
  8. int entropy_calc(long byte_count[], int length)
  9. {
  10. float entropy;
  11. float count;
  12. int i;
  13.  
  14. /* entropy calculation */
  15. for (i = 0; i < SIZE; i++)
  16. {
  17. if (byte_count[i] != 0)
  18. {
  19. count = (float) byte_count[i] / (float) length;
  20. entropy += -count * log2f(count);
  21. }
  22. }
  23. return entropy;
  24. }
  25.  
  26. int main(int argc, char **argv)
  27. {
  28. FILE *inFile;
  29. int i; // various loop index
  30. int j; // filename loop index
  31. int n; // Bytes read by fread;
  32. int length; // Filesize
  33. float count;
  34. float entropy;
  35. long byte_count[SIZE];
  36. unsigned char buffer[1024];
  37.  
  38. /* do this for all files */
  39. for(j = 1; j < argc; j++)
  40. {
  41. memset(byte_count, 0, sizeof(long) * SIZE);
  42.  
  43. inFile = fopen(argv[j], "rb"); // opens the file given on command line
  44.  
  45. if(inFile == NULL) // error-checking to see if file exists
  46. {
  47. printf("Files does not exist. `%s`n", argv[j]);
  48. continue;
  49. }
  50.  
  51. /* Read the whole file in parts of 1024 */
  52. while((n = fread(buffer, 1, 1024, inFile)) != 0)
  53. {
  54. /* Add the buffer to the alphabet */
  55. for (i = 0; i < n; i++)
  56. {
  57. byte_count[(int) buffer[i]]++;
  58. length++;
  59. }
  60. }
  61. fclose(inFile);
  62.  
  63. float entropy = entropy_calc(byte_count, length);
  64. printf("%02.5f t%sn", entropy, argv[j]);
  65. }
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement