fork download
  1. #include <stdio.h>
  2.  
  3. typedef unsigned int u32;
  4.  
  5. //
  6. // Template version, evaluated at compile time in optimised builds
  7. //
  8. template <u32 N>
  9. constexpr u32 HashFNVConst(const char(&text)[N])
  10. {
  11. return (HashFNVConst<N-1>((const char(&)[N - 1])text) ^ static_cast<u32>(text[N - 2])) * 16777619u;
  12. }
  13.  
  14. template<>
  15. constexpr u32 HashFNVConst<1>(const char(&text)[1])
  16. {
  17. return 2166136261u;
  18. }
  19.  
  20. //
  21. // Loop version, evaluated at runtime
  22. //
  23. u32 HashFNV(const char* text)
  24. {
  25. u32 hash = 2166136261u;
  26. for (const char* c=text ; *c ; ++c)
  27. {
  28. hash = hash ^ static_cast<u32>(*c);
  29. hash *= 16777619u;
  30. }
  31. return hash;
  32. }
  33.  
  34. int main()
  35. {
  36. const char * text = "Hello";
  37. printf("0x%x (Loop version)\n", HashFNV(text));
  38. printf("0x%x (Template version)\n", HashFNVConst("Hello"));
  39. return 0;
  40. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
0xf55c314b (Loop version)
0xf55c314b (Template version)