Hash functions
- C course
- Advanced
- Lesson 55/83
- 5 min
Learn hash functions and digest extraction.
Hash functions
A hash function turns data of any size into a fixed-size digest. A good hash is deterministic (same input always yields same output), one-way (you cannot recover the input from the output) and has an avalanche effect (a small input change produces a large output change).
The digest is used for data integrity: file downloads, password storage, digital signatures. In C you can write a simple hash; but for production you use a standard algorithm like SHA-256. In this lesson we will write a simple hash that sums character codes; we will see what the digest looks like.
Writing a simple hash
A simple hash: sum the character codes. Define unsigned int hash(const char *s); loop with while (*s) { h += (unsigned char)*s; s++; }. The return is h. This hash is weak but shows the concept.
For testing, print printf("digest: %u\n", hash("hello") % 100). The "hello" characters sum to 104+101+108+108+111 = 532; 532 % 100 = 32. So the output is digest: 32. This is deterministic. In production SHA-256 is used; there the digest is 32 bytes.
Practice Write a simple hash
Define a function unsigned int hash(const char *s). Inside: unsigned int h = 0;, while (*s) { h += (unsigned char)*s; s++; }, return h;. In main call printf("digest: %u\n", hash("hello") % 100);.
Starter code
#include <stdio.h>
#include <string.h>
// Write hash function
// Print digest of hello
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
unsigned int hash(const char *s) {
unsigned int h = 0;
while (*s) {
h += (unsigned char)*s;
s++;
}
return h;
}
int main(void) {
printf("digest: %u\n", hash("hello") % 100);
return 0;
}Expected output
digest: 32
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does a good hash function behave?
- Reversible
- Variable size output
- Same input same output Correct answer
- Input similar to output
Explanation: Being deterministic is the core property of a good hash.
2 Hash call
unsigned int h = hash("____");
unsigned int h = hash("merhaba");
Explanation: The merhaba string goes into the hash function.
3 Match hash concepts
| Term | Meaning |
|---|---|
digest |
Fixed size |
deterministic |
Same input same output |
one-way |
No reverse |
avalanche |
Small change big diff |