Guest User

Untitled

a guest
Jul 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.21 KB | None | 0 0
  1. using System.IO;
  2. using System.Collections.Generic;
  3.  
  4. namespace Tumultu_
  5. {
  6.     class Entropy
  7.     {
  8.         public readonly int SampleCount = 256;  //default number of samples
  9.         public readonly long FileSizeBytes;
  10.  
  11.         private FileInfo file;
  12.         private string fileName;
  13.         private string filePath;
  14.         private long sampleSizeBytes;
  15.  
  16.         public List<double> EntropyList { get; private set; }
  17.  
  18.         /// <summary>
  19.         ///     Basic constructor for "Entropy" class.
  20.         /// </summary>
  21.         ///
  22.         /// <param name="f">
  23.         ///     Handle to a file
  24.         /// </param>
  25.         ///
  26.         /// <param name="sampleCount">
  27.         ///     We want to divde file to this amount of chunks
  28.         /// </param>
  29.         public Entropy(FileInfo f, int sampleCount = 256)
  30.         {
  31.             file = f;
  32.  
  33.             FileSizeBytes = file.Length;
  34.             fileName = file.Name;
  35.             filePath = file.FullName;
  36.             SampleCount = sampleCount;  
  37.         }
  38.  
  39.         /// <summary>
  40.         ///     Count entropy of single sequence of bytes in a file
  41.         /// </summary>
  42.         /// <param name="fs">
  43.         ///     Handle to a file
  44.         /// </param>
  45.         /// <returns>
  46.         ///     Entropy of a single chunk of a file
  47.         /// </returns>
  48.         private double countSingleSampleEntropy(FileStream fs)
  49.         {
  50.             int[] arr = new int[256];
  51.  
  52.             using (fs)
  53.                 for (long i = 0; i < sampleSizeBytes; i++) arr[fs.ReadByte()]++;
  54.  
  55.             double ent = 0.0;
  56.             foreach(int x in arr)
  57.             {
  58.                 ent += ((double)x * x) / sampleSizeBytes;
  59.             }
  60.             ent = 1 - (ent / sampleSizeBytes);
  61.  
  62.             return ent * ent;
  63.         }  
  64.  
  65.         /// <summary>
  66.         ///     Counts whole file entropy and saves result to 'entropyList'.
  67.         /// </summary>
  68.         private void GetEntropy()
  69.         {
  70.             FileStream fs = File.Open(filePath, FileMode.Open);
  71.             for(int i = 0; i < SampleCount; i++)  
  72.                 EntropyList.Add(countSingleSampleEntropy(fs));
  73.            
  74.             fs.Dispose();
  75.             fs.Close();
  76.         }
  77.     }
  78. }
Add Comment
Please, Sign In to add comment