Skip to content

Instantly share code, notes, and snippets.

@Wunkolo
Created October 28, 2013 18:15
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 Wunkolo/7201789 to your computer and use it in GitHub Desktop.
Save Wunkolo/7201789 to your computer and use it in GitHub Desktop.
Compile-time Fowler–Noll–Vo hash of strings. StringHash("Test").GetHash() will be compiled into an unsigned int hash at compile-time.
template<unsigned int N, unsigned int I>
struct FnvHash
{
inline static unsigned int Hash(const char (&str)[N])
{
return (FnvHash<N,I-1>::Hash(str) ^ str[I-1]) * 16777619u;
}
};
template<unsigned int N>
struct FnvHash<N,1>
{
inline static unsigned int Hash(const char (&str)[N])
{
return (2166136261u ^ str[0]) * 16777619u;
}
};
class StringHash
{
public:
template<unsigned int N>
inline StringHash(const char (&str)[N])
: m_hash(FnvHash<N,N>::Hash(str))
{
}
unsigned int GetHash()
{
return m_hash;
}
private:
unsigned int m_hash;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment