Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Created February 22, 2026 00:18
Show Gist options
  • Select an option

  • Save jweinst1/484e97e111bdceb5f1add27615997140 to your computer and use it in GitHub Desktop.

Select an option

Save jweinst1/484e97e111bdceb5f1add27615997140 to your computer and use it in GitHub Desktop.
C++ hash variable sized byte array
#include <cstdint>
#include <cstring>
#include <cstdio>
#include <random>
#include <limits>
#include <algorithm>
#include <array>
#include <vector>
#include <cmath>
#include <map>
#include <bitset>
#include <iostream>
#include <functional>
#include <unordered_map>
namespace std {
template<size_t N>
struct hash<std::array<uint8_t, N>> {
std::size_t operator()(const std::array<uint8_t, N>& a) const noexcept {
std::size_t h = 0;
// A simple (but not necessarily the best) hash combination
// A common approach is to use a hash combining function like boost::hash_combine
// or a custom implementation. For simplicity, this example just iterates.
for (uint8_t byte : a) {
h ^= std::hash<uint8_t>{}(byte) + 0x9e3779b9 + (h << 6) + (h >> 2);
}
return h;
}
};
}
template<size_t dims>
static void printByteArr(const std::array<uint8_t, dims>& arr) {
putc('[', stdout);
for (int i = 0; i < dims; ++i)
{
printf("%u ", arr[i]);
}
putc(']', stdout);
putc('\n', stdout);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment