user198729
user198729

Reputation: 63636

How to calculate the hamming distance of two binary sequences in PHP?

hamming('10101010','01010101')

The result of the above should be 8.

How to implement it?

Upvotes: 2

Views: 5508

Answers (7)

Joyce Babu
Joyce Babu

Reputation: 20654

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;
    }

Upvotes: 2

2ge
2ge

Reputation: 281

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

Upvotes: 5

nik
nik

Reputation: 3678

Try:

echo gmp_hamdist('10101010','01010101')

Upvotes: 0

Yacoby
Yacoby

Reputation: 55445

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

Upvotes: 1

Alix Axel
Alix Axel

Reputation: 154543

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";

Upvotes: 0

Gumbo
Gumbo

Reputation: 655239

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;
}

Upvotes: 0

zaf
zaf

Reputation: 23244

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)

Upvotes: 2

Related Questions