1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
pub fn shannon_entropy(bytes: &[u8]) -> f32 {
let mut entropy = 0.0;
let mut counts = [0; 256];
for &b in bytes {
counts[b as usize] += 1;
}
for &count in counts.iter() {
if count == 0 { continue }
let p: f32 = (count as f32) / (bytes.len() as f32);
entropy -= p * p.log(2.0);
}
entropy
}
pub fn metric_entropy(bytes: &[u8]) -> f32 {
let h = shannon_entropy(bytes);
h / (bytes.len() as f32)
}
#[cfg(test)]
mod tests {
use super::shannon_entropy;
#[test]
fn test_entropy_empty() {
let h = shannon_entropy(b"");
assert_eq!(h, 0.0);
}
#[test]
fn test_entropy_a() {
let h = shannon_entropy(b"a");
assert_eq!(h, 0.0);
}
#[test]
fn test_entropy_aaaaa() {
let h = shannon_entropy(b"aaaaa");
assert_eq!(h, 0.0);
}
#[test]
fn test_entropy_ab() {
let h = shannon_entropy(b"ab");
assert_eq!(h, 1.0);
}
#[test]
fn test_entropy_aab() {
let h = shannon_entropy(b"aab");
assert_eq!(h, 0.9182958);
}
#[test]
fn test_entropy_equal_distribution1() {
let mut bytes = [0u8; 256];
for i in 0..256 {
bytes[i] = i as u8;
}
let h = shannon_entropy(&bytes);
assert_eq!(h, 8.0);
}
#[test]
fn test_entropy_equal_distribution2() {
let mut bytes = [0u8; 256*2];
for i in 0..256*2 {
bytes[i] = (i % 256) as u8;
}
let h = shannon_entropy(&bytes);
assert_eq!(h, 8.0);
}
#[test]
fn test_entropy_helloworld() {
let h = shannon_entropy(b"hello, world");
assert_eq!(h, 3.0220551);
}
}