program StringHashExample;
{$mode objfpc}{$H+}
{
Computes a hash value for a string using the djb2 algorithm.
About djb2:
- Created by Daniel J. Bernstein.
- Simple and fast.
- Commonly used in hash tables and lookup structures.
- Not suitable for cryptographic purposes such as password storage.
Returns:
A 64-bit unsigned integer hash value.
}
function HashString(const Text: string): QWord;
var
Hash: QWord;
Ch: Char;
begin
{
Initialize the hash with a fixed seed value.
The value 5381 is traditional for the djb2 algorithm and
was chosen because it results in a good distribution of
hash values for many types of text.
}
Hash := 5381;
{
Process each character in the string.
The expression:
Hash := Hash * 33 + Ord(Ch);
is the core of the djb2 algorithm.
Multiplying by 33 helps spread characters throughout
the output range, reducing collisions.
}
for Ch in Text do
Hash := ((Hash shl 5) + Hash) + Ord(Ch);
Result := Hash;
end;
var
Text: string;
HashValue: QWord;
begin
{
Example input string.
In a real application this could come from a file,
user input, database record, or network request.
}
Text := 'Hello, World!';
{
Compute the hash value.
}
HashValue := HashString(Text);
Writeln('Original string: ', Text);
Writeln('Hash value : ', HashValue);
{
Notes:
1. The same string always produces the same hash value.
2. Different strings may occasionally produce the same
hash value. This is known as a collision.
3. Hashes are primarily used for:
- Fast lookups
- Dictionaries
- Hash tables
- Caching
- Data verification
4. Hashing is not encryption.
Once a string is hashed, the original string cannot
generally be recovered from the hash value alone.
}
end.
{
run:
Original string: Hello, World!
Hash value : 5904905660241445518
}