2
hamming('10101010','01010101')

The result of the above should be 8.

How to implement it?

Qiu
  • 5,651
  • 10
  • 49
  • 56
user198729
  • 61,774
  • 108
  • 250
  • 348

7 Answers7

5

without installed GMP here is easy solution for any same-length binary strings

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
2ge
  • 269
  • 4
  • 12
2

You don't need to implement it because it already exists: http://php.net/manual/en/function.gmp-hamdist.php

(If you have GMP support)

zaf
  • 22,776
  • 12
  • 65
  • 95
2

The following function works with hex strings (equal length), longer than 32 bits.

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;
    }
Joyce Babu
  • 19,602
  • 13
  • 62
  • 97
1

If you don't have GMP support there is always something like this. Downside it only works on binary strings up to 32 bits in length.

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
Yacoby
  • 54,544
  • 15
  • 116
  • 120
0

Try:

echo gmp_hamdist('10101010','01010101')
Florent
  • 12,310
  • 10
  • 49
  • 58
nik
  • 3,688
  • 3
  • 21
  • 33
0

Try this function:

function hamming($b1, $b2) {
    $b1 = ltrim($b1, '0');
    $b2 = ltrim($b2, '0');
    $l1 = strlen($b1);
    $l2 = strlen($b2);
    $n = min($l1, $l2);
    $d = max($l1, $l2) - $n;
    for ($i=0; $i<$n; ++$i) {
        if ($b1[$l1-$i] != $b2[$l2-$i]) {
            ++$d;
        }
    }
    return $d;
}
Gumbo
  • 643,351
  • 109
  • 780
  • 844
0

You can easily code your hamming function with the help of substr_count() and the code provided in this comment on the PHP manual.

/* hamdist is equivilent to: */
echo gmp_popcount(gmp_xor($ham1, $ham2)) . "\n";
Alix Axel
  • 151,645
  • 95
  • 393
  • 500