0
0
CConceptBeginner · 3 min read

What is Hashing in C: Explanation and Example

In C, hashing is a technique to convert data like strings or numbers into a fixed-size number called a hash value. This helps quickly find or store data by using the hash value as an index in a data structure like a hash table.
⚙️

How It Works

Hashing works like a magic recipe that turns any input data into a unique number called a hash value. Imagine you have a big library of books and want to find a book quickly. Instead of searching every shelf, you use a special code (hash) that tells you exactly where the book is.

In C, a hash function takes your input (like a word or number) and calculates a number. This number is used as an address to store or find the data fast. The goal is to make this number unique for different inputs, but sometimes different inputs can produce the same number, called a collision.

💻

Example

This example shows a simple hash function that sums the ASCII values of characters in a string and uses modulo to fit the result into a small range. It prints the hash value for a given word.

c
#include <stdio.h>
#include <string.h>

unsigned int simpleHash(const char *str, unsigned int tableSize) {
    unsigned int hash = 0;
    for (int i = 0; i < (int)strlen(str); i++) {
        hash += (unsigned int)str[i];
    }
    return hash % tableSize;
}

int main() {
    const char *word = "hello";
    unsigned int tableSize = 10;
    unsigned int hashValue = simpleHash(word, tableSize);
    printf("Hash value of '%s' is: %u\n", word, hashValue);
    return 0;
}
Output
Hash value of 'hello' is: 2
🎯

When to Use

Hashing is useful when you want to store and find data quickly, like in databases, caches, or dictionaries. For example, if you want to check if a username already exists, hashing helps find it fast without searching all users.

In C, hashing is often used to build hash tables, which are fast data structures for lookup, insert, and delete operations. It is also used in cryptography and data integrity checks.

Key Points

  • Hashing converts data into a fixed-size number called a hash value.
  • A hash function calculates this number from input data.
  • Hash values help quickly find or store data in structures like hash tables.
  • Collisions happen when different inputs produce the same hash value.
  • Simple hash functions are easy to write but may cause more collisions.

Key Takeaways

Hashing in C turns data into a fixed-size number for fast access.
A hash function calculates the hash value from input data.
Hash tables use hash values to store and find data quickly.
Collisions can occur and need handling in real applications.
Simple hash functions are easy but may cause more collisions.