Search code examples
c++integerhashvarchar

Hash function for varchar ( string) in C++


I have a key of varchar(512) type , I want to hash it using the first 2 or first 3 characters of that string only. Please let me know which hash function to use in C++. I want to get hash value in numerics only. The range of number can be of long type i.e. int (64).


Solution

  • Why not just put the characters in an unsigned integer like this:

    unsigned int hash = ((unsigned int) field[0]) |
                        ((unsigned int) field[1] << 8) |
                        ((unsigned int) field[2] << 16);
    

    It's quick, simple, and you get unique values for all unique combinations of the first three letters.