Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
n_entropy.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
25#include "nilorea/n_entropy.h"
26
27#include <math.h>
28
29double n_entropy_shannon(const unsigned char* data, size_t len) {
30 size_t counts[256];
31 size_t i;
32 double h = 0.0;
33 if (!data || len == 0)
34 return 0.0;
35 for (i = 0; i < 256; i++)
36 counts[i] = 0;
37 for (i = 0; i < len; i++)
38 counts[data[i]]++;
39 for (i = 0; i < 256; i++) {
40 if (counts[i]) {
41 double p = (double)counts[i] / (double)len;
42 h -= p * log2(p);
43 }
44 }
45 return h;
46}
47
48double n_entropy_monobit(const unsigned char* data, size_t len) {
49 size_t i;
50 size_t ones = 0;
51 if (!data || len == 0)
52 return 0.0;
53 for (i = 0; i < len; i++) {
54 unsigned int b = data[i];
55 /* popcount of one byte */
56 b = b - ((b >> 1) & 0x55u);
57 b = (b & 0x33u) + ((b >> 2) & 0x33u);
58 b = (b + (b >> 4)) & 0x0Fu;
59 ones += b;
60 }
61 return (double)ones / ((double)len * 8.0);
62}
63
64double n_entropy_chi_square(const unsigned char* data, size_t len) {
65 size_t counts[256];
66 size_t i;
67 double expected, chi = 0.0;
68 if (!data || len == 0)
69 return 0.0;
70 for (i = 0; i < 256; i++)
71 counts[i] = 0;
72 for (i = 0; i < len; i++)
73 counts[data[i]]++;
74 expected = (double)len / 256.0;
75 for (i = 0; i < 256; i++) {
76 double diff = (double)counts[i] - expected;
77 chi += (diff * diff) / expected;
78 }
79 return chi;
80}
double n_entropy_shannon(const unsigned char *data, size_t len)
Shannon entropy of the byte sample, in bits per byte (0.0 .
Definition n_entropy.c:29
double n_entropy_monobit(const unsigned char *data, size_t len)
Fraction of set bits in the sample (0.0 .
Definition n_entropy.c:48
double n_entropy_chi_square(const unsigned char *data, size_t len)
Chi-square statistic of the byte histogram against a uniform distribution over 256 values.
Definition n_entropy.c:64
Randomness/entropy metrics for byte samples (token-randomness analysis)