"Johnson Lau" schreef: > I need to compare two binary numbers and need perl to return the > number of matching bits. > > For example: > > $aaa = "10111100"; > $bbb = "00101100"; > > In this case, the number of matching bits is 6.
perl -Mstrict -Mwarnings -le' my $b1 = "10111100"; my $b2 = "00101100"; $b2 =~ tr/01/10/; my $n = ($b1 & $b2) =~ tr/0/0/; print $n; ' 6 To derive the length, a prepared hash (with 256 keys) will be faster. perl -Mstrict -Mwarnings -le' my $b1 = oct "0b" . "10111100"; my $b2 = oct "0b" . "00101100"; my $n = sprintf("%08b", $b1 ^ $b2) =~ tr/0/0/; print $n; ' To derive the length, a prepared array (with 256 elements) is much faster. -- Affijn, Ruud "Gewoon is een tijger." -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] http://learn.perl.org/