Home: Perl Programming Help: Beginner:
(efficiently) calculate hamming weight of bit vector

New User

Dec 27, 2010, 1:40 PM

Views: 1595
(efficiently) calculate hamming weight of bit vector

hope you all had a wonderful Christmas and are enjoying your holidays.

I used my time to get into some perl programming around some crypto algorithms. In the course of this I came to the following question:

I have a vector of bits like vec( $bitf, $j,1);
Now I need to calculate the hamming weight, i.e. the number of 1's in the vector. To do this, I'm currently running thru a loop and look at each bit of the vector using an if statement. It works but it is also horribly slow (unfortunately my vector is pretty long).

Does anybody of you have an idea how I can get the hamming weight more efficiently?




Dec 30, 2010, 5:26 AM

Views: 1571
Re: [norbert78] (efficiently) calculate hamming weight of bit vector

How about this?

$count = (unpack("b*", $bitf) =~ tr/1//); 
print "There was $count 1's\n";

New User

Jan 1, 2011, 8:54 AM

Views: 1559
Re: [Karazam] (efficiently) calculate hamming weight of bit vector

Great! Thanks. That works out well.

It's for sure not as efficient as a solution that I found under http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation in the meantime but it's efficient enough for me.