Module: Ronin::Support::Text::Entropy

Defined in:
lib/ronin/support/text/entropy.rb

Overview

Implements the [Shanno Entropy] algorithm.

Since:

  • 1.0.0

Class Method Summary collapse

Class Method Details

.calculate(string, base: 2) ⇒ Float

Calculates the entropy for the given string.

Parameters:

  • string (String)

    The given string to calculate the entropy for.

  • base (Integer) (defaults to: 2)

    The base to calculate the entropy for.

Returns:

  • (Float)

    The entropy for the string.

Since:

  • 1.0.0



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/ronin/support/text/entropy.rb', line 44

def self.calculate(string, base: 2)
  char_counts = Hash.new(0)

  string.each_char do |char|
    char_counts[char] += 1
  end

  length  = string.length.to_f
  entropy = 0.0

  char_counts.each_value do |count|
    freq     = count / length
    entropy -= freq * Math.log(freq,base)
  end

  return entropy
end