-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.h
49 lines (40 loc) · 1.03 KB
/
utils.h
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
#ifndef UTILS_H
#define UTILS_H 1
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAXLEN 961 // maximum string length
static inline size_t makehist(unsigned char const * const buf, ssize_t * const hist, size_t len) {
ssize_t wherechar[256];
size_t i, histlen;
histlen = 0;
for (i = 0; i < 256; i++)
wherechar[i] = -1;
for (i = 0; i < len; i++) {
if (wherechar[buf[i]] == -1) {
wherechar[(int)buf[i]] = histlen;
histlen++;
}
hist[wherechar[(int)buf[i]]]++;
}
return histlen;
}
static inline float entropy(u_int8_t const * const buf, size_t len) {
float entropy = 0.0f;
u_int32_t byte_counters[256];
size_t i;
memset(byte_counters, 0, sizeof(byte_counters));
for(i = 0; i < len; ++i) {
byte_counters[buf[i]]++;
}
for(i = 0; i < sizeof(byte_counters) / sizeof(byte_counters[0]); ++i) {
if(byte_counters[i] == 0) {
continue;
}
float const p = (float)byte_counters[i] / len;
entropy += p * log2f(1 / p);
}
return entropy;
}
#endif