Re: comparing two binary numbers

[email protected] ("Dr.Ruud")
Newsgroups perl.beginners
Organization Chaos rules.
Message-ID <[email protected]>
"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."
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.