Re: comparing two binary numbers

[email protected] (sisyphus)
Newsgroups perl.beginners
Organization http://groups.google.com
Message-ID <[email protected]>
On May 11, 3:09 pm, [email protected] (Johnson Lau) wrote:
> Dear all,
>
> 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.
>

use strict;
use warnings;

use Math::GMPz qw(:mpz);

my $str1 = "10111100";
my $str2 = "00101100";

my $wanted = length($str1) - Rmpz_popcount(Math::GMPz->new($str1, 2) ^
Math::GMPz->new($str2, 2));
print $wanted, "\n";

Cheers,
Rob
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.