Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > Perl Beginners > Re: comparing t...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 3 of 7 Topic 11053 of 11532
Post > Topic >>

Re: comparing two binary numbers

by rvtol+news@[EMAIL PROTECTED] (Dr.Ruud) May 11, 2008 at 12:37 PM

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




 7 Posts in Topic:
comparing two binary numbers
johnsonlau@[EMAIL PROTECT  2008-05-11 13:09:05 
Re: comparing two binary numbers
jialinli1981@[EMAIL PROTE  2008-05-11 02:40:09 
Re: comparing two binary numbers
rvtol+news@[EMAIL PROTECT  2008-05-11 12:37:18 
Re: comparing two binary numbers
sisyphus359@[EMAIL PROTEC  2008-05-11 03:02:01 
Re: comparing two binary numbers
charley@[EMAIL PROTECTED]  2008-05-11 16:16:38 
Re: comparing two binary numbers
krahnj@[EMAIL PROTECTED]   2008-05-12 02:02:10 
Re: comparing two binary numbers
rvtol+news@[EMAIL PROTECT  2008-05-12 15:40:17 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Sat Jul 26 6:18:16 CDT 2008.