develooper Front page | perl.beginners | Postings from May 2008

Re: comparing two binary numbers

Thread Previous
From:
Li, Jialin
Date:
May 11, 2008 00:40
Subject:
Re: comparing two binary numbers
On 5/11/08, Johnson Lau <johnsonlau@cuhk.edu.hk> 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: beginners-unsubscribe@perl.org
> For additional commands, e-mail: beginners-help@perl.org
> 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.
~


Thread Previous


Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About