Gist of the Day: Counting Bits

Posted: 16th September 2013 by manchicken in Gist of the Day, Hacking, Perl
Tags: , , ,

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

  1. Brad Gilbert says:

    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. Max says:

    unpack is your friend… Try this:

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