tags:

views:

192

answers:

5
hamming('10101010','01010101')

The result of the above should be 8.

How to implement it?

+1  A: 

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
I'm using PHP5.3,but don't have php_gmp.dll
In the XAMPP for windows distribution you can find a copy: http://www.apachefriends.org/en/xampp.html
zaf
A: 

echo gmp_hamdist('10101010','01010101')

nik
Where to download php_gmp.dll for PHP5.3.0?
take a look at comments in http://www.php.net/manual/en/gmp.installation.php
binaryLV
There is no dll I need.
Do you need some special dll? Because I followed "instructions" in comments ("you need to use the VC9 build", to be exact) and there is a `ext\php_gmp.dll`.
binaryLV
Seems mine is not VC9,what can I do?
You can download VC9 version at http://windows.php.net/download/ - that's if you want to use GMP. Though, it might be easier to write a simple function that does comparison.
binaryLV
A: 

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
A: 

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
A: 

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