Base Conversion
Date : July 1, 2004
The following routines will convert a number to and from among the different bases: decimal, hexadecimal, and binary.
################################################ # Convert a binary input to hex # Does not return any leading 0s # sub bin2hex { my $inpt = shift; my $hex; my $bits = length($inpt); $inpt = (32 - $bits) x '0' . $inpt; my $dec = unpack("N", pack("B32", substr("0" x 32 . $inpt, -32))); return(sprintf("%x", $dec)); } ################################################ # Convert a decimal input to binary # Arguments = decimal_number, number_of_bits # sub dec2bin { my $dec = int(shift); my $bits = shift; my $bin = unpack("B32", pack("N", $dec)); substr($bin, 0, (32 - $bits)) = ''; return($bin); } ################################################ # Convert a binary input to decimal # sub bin2dec { my $bin = shift; my $bits = length($bin); $bin = (32 - $bits) x '0' . $bin; my $dec = unpack("N", pack("B32", substr("0" x 32 . $bin, -32))); return($dec); } ############################################### # Convert a hex input to decimal # sub hex2dec { my $h = shift; $h =~ s/^0x//g; return( hex($h)); }
Tags:
Perl