basics · intermediate · ~15 min

Hamming distance

Count differing bit positions between two values.

Challenge

Implement:

int hamming_distance(unsigned a, unsigned b);

Return the number of bit positions where a and b differ.

Input format

Two values a and b.

Output format

The count of differing bits (0..32).

Constraints

Equal values -> 0.

Starter code

#include <stddef.h>
/* Hamming distance: number of bit positions where a and b differ. */
int hamming_distance(unsigned a,unsigned b){ (void)a;(void)b; return 0; }

Common mistakes

Comparing values instead of XOR-ing then counting.

Edge cases to handle

It is symmetric: d(a,b)==d(b,a).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.