Gist of the Day: Counting Bits

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

2 thoughts on “Gist of the Day: Counting Bits”

  1. 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;

  2. unpack is your friend… Try this:
    perl -E ‘say unpack(“%32b*”, pack(“I”, shift))’ — 12412

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.