C++ 计算文件的熵
我在谷歌、论坛、维基百科和很多很多论坛上搜索这个功能已经超过两个小时了,但我找不到它。我怎么能做到?我尝试了以下方法,但没有成功C++ 计算文件的熵,c++,python,math,count,entropy,C++,Python,Math,Count,Entropy,我在谷歌、论坛、维基百科和很多很多论坛上搜索这个功能已经超过两个小时了,但我找不到它。我怎么能做到?我尝试了以下方法,但没有成功 #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <stdint.h> static unsigned int mylog2 (unsigned int val) { unsigned
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <stdint.h>
static unsigned int mylog2 (unsigned int val) {
unsigned int ret = -1;
while (val != 0) {
val >>= 1;
ret++;
}
return ret;
}
int main(int argc, char **argv)
{
FILE *pFile;
int i; // various loop index
int j; // filename loop index
int n; // Bytes read by fread;
int size; // Filesize
float entropy;
float temp; // temp value used in entropy calculation
long alphabet[256];
unsigned char buffer[1024];
/* do this for all files */
for(j = 1; j < argc; j++)
{
/* initialize all values */
size = 0;
entropy = 0.0;
memset(alphabet, 0, sizeof(long) * 256);
pFile = fopen(argv[j], "rb");
if(pFile == NULL)
{
printf("Failed to open `%s`\n", argv[j]);
continue;
}
/* Read the whole file in parts of 1024 */
while((n = fread(buffer, 1, 1024, pFile)) != 0)
{
/* Add the buffer to the alphabet */
for (i = 0; i < n; i++)
{
alphabet[(int) buffer[i]]++;
size++;
}
}
fclose(pFile);
/* entropy calculation */
for (i = 0; i < 256; i++)
{
if (alphabet[i] != 0)
{
temp = (float) alphabet[i] / (float) size;
entropy += -temp * mylog2(temp);
}
}
printf("%02.5f [ %02.5f ]\t%s\n", entropy, entropy / 8, argv[j]);
} // outer for
return 0;
}
如何在C++中实现同样的功能?希望有人能如实回答。你不能计算以2为底的对数的整数部分。要计算C中base2的对数,可以使用
math.h
中的log2
,h=-1*sum(p_i*log(p_i))
,其中p_i是每个符号i(和)的频率,如果对数基为2,则结果为每个符号的位数,如果对数基为n,则为“nats”。但是,如果您改变数据的表达方式,也就是说,如果相同的数据表示为位、字节等,则会发生变化。因此,您可以除以log(n),其中n是可用的符号数(2表示二进制,256表示字节),H的范围为0到1(这是标准化密集型香农熵)
上述熵是一种“强化”形式,即每符号,类似于物理中的每千克或每摩尔比熵。常规的“扩展”熵(如物理熵)是S=N*H
,其中N是文件中的符号数。使用上面的H进行一点数学运算,可以得到文件的标准化扩展熵,其中“n”是不同的“i”符号数(2表示二进制,256表示字节):
对于每个符号频率相同的文件,这将给出
S=N
。熵不会对数据进行任何压缩,因此完全不知道任何模式,因此000000111111具有与010111101000相同的H和S(两种情况下均为6 1和6 0)。您可能需要转换基数,但很容易做到:这些函数最早出现在glibc版本2.1中。符合C99,POSIX.1-2001的要求。变量返回双精度也符合SVr4,4.3BSD。
import sys
import math
if len(sys.argv) != 2:
print "Usage: file_entropy.py [path]filename"
sys.exit()
# read the whole file into a byte array
f = open(sys.argv[1], "rb")
byteArr = map(ord, f.read())
f.close()
fileSize = len(byteArr)
print 'File size in bytes:'
print fileSize
print
# calculate the frequency of each byte value in the file
freqList = []
for b in range(256):
ctr = 0
for byte in byteArr:
if byte == b:
ctr += 1
freqList.append(float(ctr) / fileSize)
# print 'Frequencies of each byte-character:'
# print freqList
# print
# Shannon entropy
ent = 0.0
for freq in freqList:
if freq > 0:
ent = ent + freq * math.log(freq, 2)
ent = -ent
print 'Shannon entropy (min bits per byte-character):'
print ent
print
print 'Min possible file size assuming max theoretical compression efficiency:'
print (ent * fileSize), 'in bits'
print (ent * fileSize) / 8, 'in bytes'
### Modifications to file_entropy.py to create the Histogram start here ###
### by Ken Hartman www.KennethGHartman.com
import numpy as np
import matplotlib.pyplot as plt
N = len(freqList)
ind = np.arange(N) # the x locations for the groups
width = 1.00 # the width of the bars
#fig = plt.figure()
fig = plt.figure(figsize=(11,5),dpi=100)
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, freqList, width)
ax.set_autoscalex_on(False)
ax.set_xlim([0,255])
ax.set_ylabel('Frequency')
ax.set_xlabel('Byte')
ax.set_title('Frequency of Bytes 0 to 255\nFILENAME: ' + sys.argv[1])
plt.show()
S=N * H / log(n) = sum(count_i*log(N/count_i))/log(n)