Created
October 20, 2012 19:24
-
-
Save LeviSchuck/3924453 to your computer and use it in GitHub Desktop.
Takes a string, be it statically const or not, and makes an 8-byte long
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
unsigned long attrID2(const char * ls){ | |
const unsigned long golden = 0x9E3779B97f4A7C15; | |
unsigned long result = 0; | |
int offset = 0; | |
for(int i=0; ls[i] != 0; i++,offset = (offset + 1) % sizeof(long)){ | |
const unsigned long p = ((long)ls[i] << (offset*8)); | |
const unsigned long p2 = ((long)1 << (i%(sizeof(long)*8))) & golden; | |
result = ~0 & (result ^ p ^ p2); | |
} | |
return result; | |
} | |
unsigned long constexpr attrID3(const char * ls, long val = 0, unsigned int depth = 0, unsigned int offset = 0) { | |
return *ls | |
? | |
attrID3(ls+1, | |
~0 & (val ^ ((long)*ls << (offset*8)) ^ (((long)1 << (depth%(sizeof(long)*8))) & 0x9E3779B97f4A7C15)), | |
depth+1, | |
(offset+1) % sizeof(long)) | |
: | |
val; | |
} | |
unsigned long constexpr operator "" _attr(char const * ls, std::size_t n){ | |
return attrID3(ls); | |
} | |
int main(int argc, const char * argv[]) | |
{ | |
const char * test = "Some test text here"; | |
unsigned long a,b,c,d,e,f; | |
char test2[] = "meh"; | |
a = attrID2(test); | |
b = attrID3(test); | |
c = attrID2(test2); | |
d = attrID3(test2); | |
test2[1] = 'a'; | |
e = attrID2(test2); | |
f = attrID3(test2); | |
cout << hex; | |
cout << a << endl; | |
cout << b << endl; | |
cout << c << endl; | |
cout << d << endl; | |
cout << e << endl; | |
cout << f << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment