I’m pretty sure there’s a more efficient way of doing this, but here’s what I’ve quickly typed up in 10 minutes sitting in my hotel. It just takes in a number, and then the size (in bits) of the number. It returns the number of bits it counts. I believe there is a very common algorithm called the Hamming algorithm, but as I don’t know that algorithm I’ve kinda worked this up instead.

This post is super short as I have a very busy day ahead of me. I’m going to go ahead and just post the code and call it a day. Sorry for the brief post.

### The Code

The number of bits shouldn’t be hard-coded.

sub count_bits {

my ($num) = @_;

my $return = 0;

my $k = 0;

while($num) {

my $test = (1 << $k);

if (0+$num & $test) {

$num ^= $test;

$return += 1;

}

$k ++;

}

return $return;

}

unpack is your friend… Try this:

perl -E ‘say unpack(“%32b*”, pack(“I”, shift))’ — 12412