Skip to content

Instantly share code, notes, and snippets.

@vivkin
Last active December 31, 2015 15:18
Show Gist options
  • Save vivkin/8005639 to your computer and use it in GitHub Desktop.
Save vivkin/8005639 to your computer and use it in GitHub Desktop.
Compile time CRC32, Bernstein and FNV1a hash functions
constexpr unsigned int CRC32_TABLE[] = {
0x00000000, 0x1DB71064, 0x3B6E20C8, 0x26D930AC, 0x76DC4190, 0x6B6B51F4, 0x4DB26158, 0x5005713C,
0xEDB88320, 0xF00F9344, 0xD6D6A3E8, 0xCB61B38C, 0x9B64C2B0, 0x86D3D2D4, 0xA00AE278, 0xBDBDF21C
};
constexpr unsigned int crc32_4(char c, unsigned int h) { return (h >> 4) ^ CRC32_TABLE[(h & 0xF) ^ c]; }
constexpr unsigned int crc32(const char *s, unsigned int h = ~0) { return !*s ? ~h : crc32(s + 1, crc32_4(*s >> 4, crc32_4(*s & 0xF, h))); }
constexpr unsigned int djb2a(const char *s, unsigned int h = 5381) { return !*s ? h : djb2a(s + 1, 33 * h ^ *s); }
constexpr unsigned int fnv1a(const char *s, unsigned int h = 0x811c9dc5) { return !*s ? h : fnv1a(s + 1, (h ^ *s) * 0x01000193); }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment