Tuesday, October 19, 2004

Converting Between Binary and Decimal in Perl

Recipe 2.4. Converting Between Binary and Decimal: "To convert a Perl integer to a text string of ones and zeros, first pack the integer into a number in network byte order[1] (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;

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

No comments: