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,404 questions

56,370 answers

573 users

How to hash a string and detect collision in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

/*
    djb2 hash function

    Converts a string into an unsigned long value.

    Note:
    Different strings can sometimes produce
    the same hash value (collision).
*/
unsigned long hash(const char *str)
{
    unsigned long hash = 5381;
    int c;

    while ((c = *str++)) {
        hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
    }

    return hash;
}

int main(void)
{
    const char *str1 = "Hello";
    const char *str2 = "World";

    unsigned long hash1 = hash(str1);
    unsigned long hash2 = hash(str2);

    printf("String 1: %s\n", str1);
    printf("Hash 1  : %lu\n\n", hash1);

    printf("String 2: %s\n", str2);
    printf("Hash 2  : %lu\n\n", hash2);

    /*
        First compare hashes.

        Hash comparison is very fast because
        it compares two numbers.
    */
    if (hash1 == hash2)
    {
        printf("Hashes match.\n");

        /*
            IMPORTANT:

            A matching hash does NOT guarantee
            the strings are equal.

            We must compare the actual strings
            to detect collisions.
        */
        if (strcmp(str1, str2) == 0) {
            printf("Strings are identical.\n");
        }
        else {
            printf("Hash collision detected!\n");
        }
    }
    else
    {
        printf("Hashes are different.\n");
        printf("Strings are different.\n");
    }

    return 0;
}



/*
run:

String 1: Hello
Hash 1  : 210676686969

String 2: World
Hash 2  : 210694841677

Hashes are different.
Strings are different.

*/

 



answered 2 days ago by avibootz
...