It depends on what you want your hash to do. Most hashes are used to preserve data integrity. Basically, any change to the input should result in a different output, while two different inputs should not result in the same output.
Code:
unsigned char hash1(char pwd[])
{
int idx,total=0;
for (idx=0; idx < strlen(pwd); idx++)
total += pwd[idx] + (42 - idx);
return(total % 256);
}
This kind of hash has the unfortunate property of commutivity. Try running the strings "welcome" and "leewcom" through it. They both yield the same value. (Not to mention that strlen is used in the for loop condition. You should assign the size to a temporary variable so that you don't recalc the length every loop.)
Code:
unsigned char hash2(char pwd[])
{
unsigned int idx,total=1;
for (idx=0; idx < strlen(pwd); idx++)
total += (pwd[idx] >> (idx+1)) * (pwd[idx] << (idx+1));
for (idx=0; idx < strlen(pwd); idx++)
total *= pwd[idx] % (pwd[idx] >> (idx+1));
return(total % 256);
}
Interesting, but unusable. The % operator may (and does with an input of "welcome") hit a divide by 0.
The overall goal of a hash is to create a number that depends on both the order and the value of the data passed in. This is most easily accomplished using bitwise operators. Consider the following "hash":
Code:
unsigned char hash3(char pwd[])
{
unsigned int idx,total=0;
unsigned int size = strlen(pwd);
for (idx=0; idx < size; idx++)
total = (total << 1) ^ pwd[idx];
return total;
}
This is both order- and value-dependent. With inputs "Welcome" and "eWlcome", the output is 187 and 123. Note that with an 8-bit hash, there will be a significant number of collisions (two inputs that result in the same output).
I recommend the following link for a more indepth discussion: http://www.geocities.com/SiliconVall...s/8659/crc.htm.