How to calculate the humming distance of two binary sequences in PHP?
7 replies
no GMP established here's a simple solution for any binary strings of the same length
function HammingDistance($bin1, $bin2) {
$a1 = str_split($bin1);
$a2 = str_split($bin2);
$dh = 0;
for ($i = 0; $i < count($a1); $i++)
if($a1[$i] != $a2[$i]) $dh++;
return $dh;
}
echo HammingDistance('10101010','01010101'); //returns 8
+5
a source to share
You don't need to implement it as it already exists: http://php.net/manual/en/function.gmp-hamdist.php
(If you have GMP support)
+2
a source to share
If you don't have GMP support, there is always something like this. At the bottom, it only works with binary strings up to 32 bits long.
function hamdist($x, $y){
for($dist = 0, $val = $x ^ $y; $val; ++$dist){
$val &= $val - 1;
}
return $dist;
}
function hamdist_str($x, $y){
return hamdist(bindec($x), bindec($y));
}
echo hamdist_str('10101010','01010101'); //8
+1
a source to share
The following function works with hexadecimal strings (equal to length) that are more than 32 bits long.
function hamming($hash1, $hash2) {
$dh = 0;
$len1 = strlen($hash1);
$len2 = strlen($hash2);
$len = 0;
do {
$h1 = hexdec(substr($hash1, $len, 8));
$h2 = hexdec(substr($hash2, $len, 8));
$len += 8;
for ($i = 0; $i < 32; $i++) {
$k = (1 << $i);
if (($h1 & $k) !== ($h2 & $k)) {
$dh++;
}
}
} while ($len < $len1);
return $dh;
}
+1
a source to share
With help substr_count()
and code provided in this PHP manual comment .
/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
0
a source to share