-
Notifications
You must be signed in to change notification settings - Fork 0
/
ent.c
286 lines (238 loc) · 7.82 KB
/
ent.c
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
ENT -- Entropy calculation and analysis of putative
random sequences.
Designed and implemented by John "Random" Walker in May 1985.
Multiple analyses of random sequences added in December 1985.
Bit stream analysis added in September 1997.
Terse mode output, getopt() command line processing,
optional stdin input, and HTML documentation added in
October 1998.
Documentation for the -t (terse output) option added
in July 2006.
Replaced table look-up for chi square to probability
conversion with algorithmic computation in January 2008.
For additional information and the latest version,
see http://www.fourmilab.ch/random/
Forked by NetSrv Consulting Ltd in 2014.
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#else
#include <unistd.h>
#endif
#include "iso8859.h"
#include "randtest.h"
#define UPDATE "January 28th, 2008"
#define FALSE 0
#define TRUE 1
#ifdef M_PI
#define PI M_PI
#else
#define PI 3.14159265358979323846
#endif
extern double pochisq(const double ax, const int df);
/* HELP -- Print information on how to call */
static void help(void)
{
printf("ent -- Calculate entropy of file. Call");
printf("\n with ent [options] [input-file]");
printf("\n");
printf("\n Options: -b Treat input as a stream of bits");
printf("\n -c Print occurrence counts");
printf("\n -f Fold upper to lower case letters");
printf("\n -t Terse output in CSV format");
printf("\n -u Print this message\n");
printf("\nBy John Walker");
printf("\n http://www.fourmilab.ch/");
printf("\n %s\n", UPDATE);
}
/* GETOPT -- Dumb version of getopt for brain-dead Windows. */
#ifdef _WIN32
static int optind = 1;
static int getopt(int argc, char *argv[], char *opts)
{
static char *opp = NULL;
int o;
while (opp == NULL) {
if ((optind >= argc) || (*argv[optind] != '-')) {
return -1;
}
opp = argv[optind] + 1;
optind++;
if (*opp == 0) {
opp = NULL;
}
}
o = *opp++;
if (*opp == 0) {
opp = NULL;
}
return strchr(opts, o) == NULL ? '?' : o;
}
#endif
/* Main program */
int main(int argc, char *argv[])
{
int i, oc, opt;
long ccount[256]; /* Bins to count occurrences of values */
long totalc = 0; /* Total character count */
char *samp;
double montepi, chip,
scc, ent, mean, chisq;
FILE *fp = stdin;
int counts = FALSE, /* Print character counts */
fold = FALSE, /* Fold upper to lower */
binary = FALSE, /* Treat input as a bitstream */
terse = FALSE; /* Terse (CSV format) output */
while ((opt = getopt(argc, argv, "bcftu?BCFTU")) != -1) {
switch (toISOlower(opt)) {
case 'b':
binary = TRUE;
break;
case 'c':
counts = TRUE;
break;
case 'f':
fold = TRUE;
break;
case 't':
terse = TRUE;
break;
case '?':
case 'u':
help();
return 0;
}
}
if (optind < argc) {
if (optind != (argc - 1)) {
printf("Duplicate file name.\n");
help();
return 2;
}
if ((fp = fopen(argv[optind], "rb")) == NULL) {
printf("Cannot open file %s\n", argv[optind]);
return 2;
}
}
#ifdef _WIN32
/** Warning! On systems which distinguish text mode and
binary I/O (MS-DOS, Macintosh, etc.) the modes in the open
statement for "fp" should have forced the input file into
binary mode. But what if we're reading from standard
input? Well, then we need to do a system-specific tweak
to make sure it's in binary mode. While we're at it,
let's set the mode to binary regardless of however fopen
set it.
The following code, conditional on _WIN32, sets binary
mode using the method prescribed by Microsoft Visual C 7.0
("Monkey C"); this may require modification if you're
using a different compiler or release of Monkey C. If
you're porting this code to a different system which
distinguishes text and binary files, you'll need to add
the equivalent call for that system. */
_setmode(_fileno(fp), _O_BINARY);
#endif
samp = binary ? "bit" : "byte";
memset(ccount, 0, sizeof ccount);
/* Initialise for calculations */
rt_init(binary);
/* Scan input file and count character occurrences */
while ((oc = fgetc(fp)) != EOF) {
unsigned char ocb;
if (fold && isISOalpha(oc) && isISOupper(oc)) {
oc = toISOlower(oc);
}
ocb = (unsigned char) oc;
totalc += binary ? 8 : 1;
if (binary) {
int b;
unsigned char ob = ocb;
for (b = 0; b < 8; b++) {
ccount[ob & 1]++;
ob >>= 1;
}
} else {
ccount[ocb]++; /* Update counter for this bin */
}
rt_add(&ocb, 1);
}
fclose(fp);
/* Complete calculation and return sequence metrics */
rt_end(&ent, &chisq, &mean, &montepi, &scc);
/* Calculate probability of observed distribution occurring from
the results of the Chi-Square test */
chip = pochisq(chisq, (binary ? 1 : 255));
if (terse) {
/* Count,Entropy,Chi-square,Chi-probability,Mean,Monte-Carlo-Pi,Serial-Correlation*/
printf("%ld,%f,%f,%f,%f,%f,%f\n",
totalc, ent, chisq, chip, mean, montepi, scc);
}
/* Print bin counts if requested */
if (counts) {
if (terse) {
printf("2,Value,Occurrences,Fraction\n");
} else {
printf("Value Char Occurrences Fraction\n");
}
for (i = 0; i < (binary ? 2 : 256); i++) {
if (terse) {
printf("3,%d,%ld,%f\n", i,
ccount[i], ((double) ccount[i] / totalc));
} else {
if (ccount[i] > 0) {
printf("%3d %c %10ld %f\n", i,
/* The following expression shows ISO 8859-1
Latin1 characters and blanks out other codes.
The test for ISO space replaces the ISO
non-blanking space (0xA0) with a regular
ASCII space, guaranteeing it's rendered
properly even when the font doesn't contain
that character, which is the case with many
X fonts. */
(!isISOprint(i) || isISOspace(i)) ? ' ' : i,
ccount[i], ((double) ccount[i] / totalc));
}
}
}
if (!terse) {
printf("\nTotal: %10ld %f\n\n", totalc, 1.0);
}
}
/* Print calculated results */
if (!terse) {
printf("Entropy = %f bits per %s.\n", ent, samp);
printf("\nOptimum compression would reduce the size\n");
printf("of this %ld %s file by %d percent.\n\n", totalc, samp,
(short) ((100 * ((binary ? 1 : 8) - ent) /
(binary ? 1.0 : 8.0))));
printf(
"Chi square distribution for %ld samples is %1.2f, and randomly\n",
totalc, chisq);
if (chip < 0.0001) {
printf("would exceed this value less than 0.01 percent of the times.\n\n");
} else if (chip > 0.9999) {
printf("would exceed this value more than than 99.99 percent of the times.\n\n");
} else {
printf("would exceed this value %1.2f percent of the times.\n\n",
chip * 100);
}
printf(
"Arithmetic mean value of data %ss is %1.4f (%.1f = random).\n",
samp, mean, binary ? 0.5 : 127.5);
printf("Monte Carlo value for Pi is %1.9f (error %1.2f percent).\n",
montepi, 100.0 * (fabs(PI - montepi) / PI));
printf("Serial correlation coefficient is ");
if (scc >= -99999) {
printf("%1.6f (totally uncorrelated = 0.0).\n", scc);
} else {
printf("undefined (all values equal!).\n");
}
}
return 0;
}