Rizin
unix-like reverse engineering framework and cli tools
entropy.c
Go to the documentation of this file.
1 // SPDX-FileCopyrightText: 2021 deroad <wargio@libero.it>
2 // SPDX-License-Identifier: LGPL-3.0-only
3 
4 #include "entropy.h"
5 #include <stdlib.h>
6 #include <math.h>
7 #include <rz_util/rz_assert.h>
8 
10  rz_return_val_if_fail(ctx, false);
11  memset(ctx, 0, sizeof(RzEntropy));
12  return true;
13 }
14 
15 bool rz_entropy_update(RzEntropy *ctx, const ut8 *data, size_t len) {
16  rz_return_val_if_fail(ctx && data, false);
17  for (size_t i = 0; i < len; i++) {
18  ctx->count[data[i]]++;
19  }
20  ctx->size += len;
21  return true;
22 }
23 
24 bool rz_entropy_final(ut8 *digest, RzEntropy *ctx, bool fraction) {
25  rz_return_val_if_fail(ctx && digest, false);
26  double p, entropy = 0.0;
27  ut64 count;
28  for (size_t i = 0; i < 256; i++) {
29  count = ctx->count[i];
30  if (count) {
31  p = ((double)count) / ctx->size;
32  entropy -= p * log2(p);
33  }
34  }
35  if (fraction && ctx->size) {
36  entropy /= log2((double)RZ_MIN(ctx->size, 256));
37  }
38  rz_write_be_double(digest, entropy);
39  return true;
40 }
size_t len
Definition: 6502dis.c:15
lzma_index ** i
Definition: index.h:629
static static sync static getppid static getegid const char static filename char static len const char char static bufsiz static mask static vfork const void static prot static getpgrp const char static swapflags static arg static fd static protocol static who struct sockaddr static addrlen static backlog struct timeval struct timezone static tz const struct iovec static count static mode const void const struct sockaddr static tolen const char static pathname void count
Definition: sflib.h:98
bool rz_entropy_init(RzEntropy *ctx)
Definition: entropy.c:9
bool rz_entropy_final(ut8 *digest, RzEntropy *ctx, bool fraction)
Definition: entropy.c:24
bool rz_entropy_update(RzEntropy *ctx, const ut8 *data, size_t len)
Definition: entropy.c:15
uint8_t ut8
Definition: lh5801.h:11
return memset(p, 0, total)
void * p
Definition: libc.cpp:67
#define rz_return_val_if_fail(expr, val)
Definition: rz_assert.h:108
static void rz_write_be_double(void *dest, double val)
Definition: rz_endian.h:171
#define RZ_MIN(x, y)
ut64(WINAPI *w32_GetEnabledXStateFeatures)()