Stuart's Useful Perl Pages

Binary to decimal conversion

To convert from binary to decimal numbers use:

$decimalnum = bin2dec($binarynum);

# Convert a binary number to a decimal number
sub bin2dec {
	unpack("N", pack("B32", substr("0" x 32 . shift, -32)));

Or to go the other way around:

$binarynum = dec2bin($decimalnum);

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