Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to hash a string in Pascal

1 Answer

0 votes
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

}

 



answered 1 day ago by avibootz
...