Skip to content

Instantly share code, notes, and snippets.

@uucidl
Created December 28, 2016 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uucidl/c38b0e3c713bb38b72412fc268dda911 to your computer and use it in GitHub Desktop.
Save uucidl/c38b0e3c713bb38b72412fc268dda911 to your computer and use it in GitHub Desktop.
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
size_t
megabytes_size(uint32_t x)
{
return x * 1024 * 1024;
}
struct occurence_histograms
{
size_t bits[2];
size_t nibbles[16];
size_t bytes[256];
};
void
collect_occurences(uint8_t* data, size_t data_size, occurence_histograms* occurence_histograms)
{
memset(occurence_histograms->bytes, 0, sizeof occurence_histograms->bytes);
memset(occurence_histograms->nibbles, 0, sizeof occurence_histograms->nibbles);
memset(occurence_histograms->bits, 0, sizeof occurence_histograms->bits);
{
uint8_t* f = data;
uint8_t* l = data + data_size;
while (f != l) {
uint8_t byte = *f;
++occurence_histograms->bytes[byte];
uint8_t nibble = byte;
++occurence_histograms->nibbles[nibble & 0xF];
nibble >>= 4;
++occurence_histograms->nibbles[nibble & 0xF];
uint8_t bit = byte;
for (size_t bit_index = 0; bit_index < 8; ++bit_index) {
++occurence_histograms->bits[bit & 1];
bit >>= 1;
}
++f;
}
}
}
void
print_occurences(occurence_histograms const* occurence_histograms)
{
printf("'byte';'occurrence'\n");
{
size_t byte = 0;
while (byte < 256) {
printf("'%lx';%lu\n", byte, occurence_histograms->bytes[byte]);
++byte;
}
}
printf("'nibble';'occurrence'\n");
{
size_t nibble = 0;
while (nibble < 16) {
printf("'%lx';%lu\n", nibble, occurence_histograms->nibbles[nibble]);
++nibble;
}
}
printf("'bits';'occurrence'\n");
{
size_t bit = 0;
while (bit < 2) {
printf("'%lx';%lu\n", bit, occurence_histograms->bits[bit]);
++bit;
}
}
}
int
main(int argc, char** argv)
{
size_t words_size = megabytes_size(64);
uint8_t *words = (uint8_t*)malloc(words_size);
occurence_histograms words_histogram;
collect_occurences(words, words_size, &words_histogram);
puts("bytes returned by malloc");
print_occurences(&words_histogram);
puts("---");
occurence_histograms histogram_histogram;
collect_occurences((uint8_t*)&words_histogram, sizeof words_histogram, &histogram_histogram);
puts("bytes inside the memory histogram");
print_occurences(&histogram_histogram);
puts("---");
puts("bytes inside main function");
occurence_histograms main_histogram;
collect_occurences((uint8_t*)
main, ((uint8_t*)&&exit)-((uint8_t*)main), &main_histogram);
print_occurences(&main_histogram);
exit:
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment