CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



norbert78
New User

Dec 27, 2010, 1:40 PM

Post #1 of 3 (947 views)
(efficiently) calculate hamming weight of bit vector Can't Post

Hello,
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?

Thx

Norbert


Karazam
User

Dec 30, 2010, 5:26 AM

Post #2 of 3 (923 views)
Re: [norbert78] (efficiently) calculate hamming weight of bit vector [In reply to] Can't Post

How about this?

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



norbert78
New User

Jan 1, 2011, 8:54 AM

Post #3 of 3 (911 views)
Re: [Karazam] (efficiently) calculate hamming weight of bit vector [In reply to] Can't Post

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.

Rgds
Norbert

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives