#!/usr/bin/env perl use utf8; ############################################################################### # This program illustrates conversion of numbers to different bases. # # Copyright © 2020 Richard Lesh. All rights reserved. ############################################################################### use Utils; use strict; use warnings; our $SYMBOLS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]; sub convert_to_base { my ($i, $base) = @_; my $result = ""; if ($i == 0) { return "0"; } my $x = $i; while ($x > 0) { my $DIGIT = $x % $base; $result = $SYMBOLS->[$DIGIT] . $result; $x = int($x / $base); } return $result; } our $SUBSCRIPT0 = 0x2080; sub compose_subscript { my ($base) = @_; my $result = ""; my $x = $base; while ($x > 0) { $result = chr($SUBSCRIPT0 + ($x % 10)) . $result; $x = int($x / 10); } return $result; } MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); if (scalar(@ARGV) != 2) { print Utils::messageFormat("Syntax: \{0:s\} max base", "BaseConversion"), "\n"; exit 1; } my $MAX = Utils::stoiWithDefault($ARGV[0], 64); my $BASE = Utils::stoiWithDefault($ARGV[1], 16); for (my $i = 0; $i <= $MAX; ++$i) { print Utils::messageFormat("\{0:d\} = \{2:s\}\{1:s\}", $i, compose_subscript($BASE), convert_to_base($i, $BASE)), "\n"; } }