Converting Between Binary and Decimal

Problem

You have an integer whose binary representation you’d like to print out, or a binary representation that you’d like to convert into an integer. You might want to do this if you were displaying non-textual data, such as what you get from interacting with certain system programs and functions.

Solution

To convert a Perl integer to a text string of ones and zeros, first pack the integer into a number in network byte order[3] (the "N" format), then unpack it again bit by bit (the "B32" format).

sub dec2bin {
    my $str = unpack("B32", pack("N", shift));
    $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
    return $str;
}

To convert a text string of ones and zeros to a Perl integer, first massage the string by padding it with the right number of zeros, then just reverse the previous procedure.

sub bin2dec {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}

Discussion

We’re talking about converting between strings like "00100011" and numbers like 35. The string is the binary representation of the number. We can’t solve either problem with sprintf (which doesn’t have a “print this in binary” format), so we have to resort to Perl’s pack and unpack functions for manipulating strings of data.

The pack and unpack functions act on strings. You can treat the string as a series of bits, bytes, integers, long integers, floating-point numbers in IEEE representation, checksums— among other strange things. The pack and unpack functions ...

Get Perl Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.