如何计算文件的熵? [英] How to calculate the entropy of a file?

查看:28
本文介绍了如何计算文件的熵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算文件的熵?(或者我们只是说一堆字节)
我有一个想法,但我不确定它在数学上是否正确.

How to calculate the entropy of a file? (Or let's just say a bunch of bytes)
I have an idea, but I'm not sure that it's mathematically correct.

我的想法如下:

  • 创建一个包含 256 个整数(全为零)的数组.
  • 遍历文件和它的每个字节,
    增加数组中的对应位置.
  • 最后:计算数组的平均值".
  • 用零初始化计数器,
    并且对于数组的每个条目:
    添加条目的差异到柜台平均".

好吧,现在我被卡住了.如何以这种方式投影"计数器结果所有结果都在 0.0 和 1.0 之间?但我确定,无论如何,这个想法是不一致的......

Well, now I'm stuck. How to "project" the counter result in such a way that all results would lie between 0.0 and 1.0? But I'm sure, the idea is inconsistent anyway...

我希望有人有更好更简单的解决方案吗?

I hope someone has better and simpler solutions?

注意:我需要整个事情来对文件的内容做出假设:
(明文、标记、压缩或一些二进制文件,...)

推荐答案

  • 最后:计算数组的平均值".
  • 用零初始化计数器,并且对于数组的每个条目:将条目与平均"的差异添加到计数器中.

通过一些修改,您可以获得香农熵:

With some modifications you can get Shannon's entropy:

将平均"重命名为熵"

(float) entropy = 0
for i in the array[256]:Counts do 
  (float)p = Counts[i] / filesize
  if (p > 0) entropy = entropy - p*lg(p) // lgN is the logarithm with base 2

正如 Wesley 提到的,我们必须将熵除以 8 才能在 0 范围内调整它..1(或者,我们可以使用对数底数 256).

As Wesley mentioned, we must divide entropy by 8 in order to adjust it in the range 0 . . 1 (or alternatively, we can use the logarithmic base 256).

这篇关于如何计算文件的熵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆