Non-decimal radices/Convert: Difference between revisions
Content added Content deleted
Underscore (talk | contribs) (Added Perl example.) |
|||
Line 264: | Line 264: | ||
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26. |
i = +('0x'+s) //hexadecimal base 16, if s='1a' then i=26. |
||
</pre> |
</pre> |
||
=={{header|Perl}}== |
|||
Perl has some built-in capabilites for various conversions between decimal, hexadecimal, octal, and binary, but not other bases. |
|||
<perl>sub digitize |
|||
# Converts an integer to a single digit. |
|||
{my $i = shift; |
|||
return $i < 10 |
|||
? $i |
|||
: ('a' .. 'z')[$i - 10];} |
|||
sub undigitize |
|||
# Converts a digit to an integer. |
|||
{my $i = shift; |
|||
return $i =~ /\d/ |
|||
? $i |
|||
: 10 + ord($i) - ord('a');} |
|||
sub to_base |
|||
{my ($int, $radix) = @_; |
|||
my $numeral = digitize($int % $radix); |
|||
$numeral .= digitize($int % $radix) |
|||
while $int = int($int / $radix); |
|||
return scalar reverse $numeral;} |
|||
sub from_base |
|||
{my ($numeral, $radix) = @_; |
|||
$numeral = reverse $numeral; |
|||
my $int = 0; |
|||
for (my $n = 0 ; $numeral ; ++$n) |
|||
{$int += $radix**$n * undigitize substr($numeral, 0, 1, '');} |
|||
return $int;}</perl> |
|||
=={{header|Python}}== |
=={{header|Python}}== |