CGI/Perl Guide | Learning Center | Forums | Advertise | Login Site Search: in Perl Guide PerlGuru Forums Learning Ctr
 MAIN INDEX SEARCHPOSTS WHO'S ONLINE 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 (1657 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 (1633 views)
 Re: [norbert78] (efficiently) calculate hamming weight of bit vector [In reply to] Can't Post
 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 (1621 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

 Announcements     PerlGuru Announcements Perl Programming Help     Frequently Asked Questions     Beginner     Intermediate     Advanced     Regular Expressions     mod_perl     DBI     Win32 Programming Help Fun With Perl     Perl Quizzes - Learn Perl the Fun Way     Perl Golf     Perl Poetry Need a Custom or Prewritten Perl Program?     I need a program that...     I Need a Programmer for Freelance Work     Throw Down The Gauntlet General Discussions     General Questions     Feedback     Tutorial/Article Suggestions for The Learning Cent     Internet Security Other Programming Languages     Javascript     PHP

 Search this forum this category all forums for All words Any words Whole Phrase (options) Powered by Gossamer Forum v.1.2.0