Re: comparing two binary numbers

[email protected] ("Li, Jialin")
Newsgroups perl.beginners
Message-ID <[email protected]>
On 5/11/08, Johnson Lau <[email protected]> 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.
>
> I know I could split the strings and compare the bits one by one.
> However, is there any faster functions for this? I need to compare
> millions of such strings with 1000 bits for each.
>
> Thanks a lot!!
>
> Johnson Lau
>
> --
> To unsubscribe, e-mail: [email protected]
> For additional commands, e-mail: [email protected]
> http://learn.perl.org/




I think what you need is counting how many ones in the xnor calculation of
two binary numbers
I cannot find xnor in Perl, only using xor, then counting how many ones,
that is the number of different bits

As the binary numbers are of 1000 bits, I think you should use Bit::Vector.
here is the code:


use strict;
use warnings;

use Bit::Vector;

use constant NSIZE => 8;

my $aaa = "10111100";
my $bbb = "00101100";

my $a = Bit::Vector->new(NSIZE);
my $b = Bit::Vector->new(NSIZE);
my $c = Bit::Vector->new(NSIZE);

$a->from_Bin($aaa);
$b->from_Bin($bbb);
$c->Xor($a, $b);
my $count = ( $c->to_Bin() =~ tr/1//);
print $count;

__END__



I did not benchmark to test the speed benefits of this method.
~
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.