1 /* $Id: hamming.c,v 1.3 2004/11/29 22:08:48 jose Exp $ */
2 
3 #include <stdlib.h>
4 #include <string.h>
5 
6 /*
7    R. W. Hamming, "Error Detecting and Error Correcting Codes", Bell System
8    Tech Journal, 9, 147-160, April 1950.
9 
10    The Hamming distance H is defined only for strings of the same length.
11    For two strings s and t, H(s, t) is the number of places in which the
12    two string differ, i.e., have different characters.
13  */
14 
15 int
hamming_d(const void * d1,size_t len1,const void * d2,size_t len2)16 hamming_d(const void *d1, size_t len1, const void *d2, size_t len2)
17 {
18 	int             H = 0, n, m;
19 	char           *s, *t;
20 
21 	s = (char *) d1;
22 	t = (char *) d2;
23 	n = len1;
24 	m = len2;
25 
26 	/* strings must be of equal size and non-zero length */
27 	if (n == 0 || (n != m))
28 		return -1;
29 
30 	/* strings equal? */
31 	if (strncmp(s, t, n) == 0)
32 		return 0;
33 
34 	while (*s != NULL) {
35 		if (strncmp(s, t, 1) != 0)
36 			H++;
37 		s++;
38 		t++;
39 	}
40 
41 	return (H);
42 }
43