Skip to content

Instantly share code, notes, and snippets.

@twoscomplement
Last active April 10, 2017 07:50
Show Gist options
  • Save twoscomplement/80c164be5cad7f51939e512f0142a5eb to your computer and use it in GitHub Desktop.
Save twoscomplement/80c164be5cad7f51939e512f0142a5eb to your computer and use it in GitHub Desktop.
CRC tables, generated at compile time using C++11 constexpr, C++14 utility library, variadic template, initializer list
// CRC tables, generated at compile time using C++11 constexpr, C++14 utility library, variadic template, initializer list
// Compiled and tested using msvc 2015, gcc 6.2, and clang 3.9.0.
// clang requires -std=c++14 -ftemplate-depth=512
#include <stdint.h>
#include <utility>
template<typename T, T Poly>
struct CrcTable {
static constexpr T Generate(T v, int r = 8) {
return r == 0 ? v : Generate((v >> 1) ^ (v & 1 ? Poly : 0), r - 1);
}
T m_V[256];
template<T ...Is>
constexpr CrcTable(std::integer_sequence<T, Is...>) : m_V{ Generate(Is)... } {}
constexpr CrcTable() : CrcTable(std::make_integer_sequence<T, 256>()) {}
constexpr T operator[](int i) const { return m_V[i]; }
};
constexpr CrcTable<uint32_t, 0xEDB88320> kCrcTable32;
constexpr CrcTable<uint64_t, 0xC96C5795D7870F42> kCrcTable64;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment