Decimal to binary convertion in Perl

This is a simple thing, but when you need it – you need it. There is no need in implementing a function that does or looking for a module at CPAN. All you are looking for is already there.

#!/usr/bin/perl -w

use strict;

# Get the number from the command line or use default.
my $number = shift || 42;

printf "%b\n", $number;

You might want to refresh you memory of printf or sprintf by flipping though the manual pages.

P.S.: 42 decimal = 101010 binary. Is it cool or what?

7 thoughts on “Decimal to binary convertion in Perl”


  1. What about the Cypriot reaction to their victorious tennis superstar way down in Melbourne, Australia. I heard Limassol went bananas about their boy Marcos.


  2. This posting has helped me out multiple times. leonid++

    My hunch is that what Randal was responding to in the original post was something like this:

    printf(“%0b\n”, $number);

    While Randal’s response is true in the strict sense, I found that in an actual use case I wanted both the parentheses and the ‘0’ between the ‘%’ and the ‘b’. Given a decimal number which I was told was a bitsum, I needed to convert it into an 8-digit binary number and then treat the digits of the binary number as indices of an array. And since that array needed to be reversed, I needed to make sure that I had a ‘0’ or a ‘1’ in each position; I couldn’t have empty strings. The parens in the ‘sprintf’ make the code inside the ‘unpack’ more readable.

    sub get_decoded {
    my $demos = shift;
    my @vals = reverse unpack(
    “bbbbbbbb”,
    sprintf(“%08b”, $demos->[37] || 0)
    );
    my %decoded;
    my @needed = qw( western eastern southern );
    my @bitfields = qw( 3 4 7 );
    @decoded{@needed} = map { $vals[$_] ? ‘Y’ : ” } @bitfields;
    return \%decoded;
    }


  3. #!/user/local/bin/perl
    print “\nEnter the num:”;
    @rem=();
    $dec =;

    print “converting to binary”;

    while ($dec> 0)
    {
    @rem[$i++] = $dec % 2;
    $dec= int ($dec/2);

    }
    print reverse(@rem);

Leave a Reply to Saswato Biswas Cancel reply