[ad_1]

How would one convert the string `789`

into a number?

Well, 789 is equal to

7 × 10^{2} + 8 × 10^{1} + 9 × 10^{0}

But we’re writing a program and we’ll want to take advantage of looping.

( ( 7 ) × 10 + 8 ) × 10 + 9

Better yet,

( ( ( 0 ) × 10 + 7 ) × 10 + 8 ) × 10 + 9

We don’t start with digits `7`

, `8`

and `9`

, but their string representation.

```
(
(
(
0
) × 10 + [ offset of "7" in "0123456789" ]
) × 10 + [ offset of "8" in "0123456789" ]
) × 10 + [ offset of "9" in "0123456789" ]
```

And finally, let’s remove the last bit of reliance on base 10.

```
(
(
(
0
) × [ number of symbols in "0123456789" ] + [ offset of "7" in "0123456789" ]
) × [ number of symbols in "0123456789" ] + [ offset of "8" in "0123456789" ]
) × [ number of symbols in "0123456789" ] + [ offset of "9" in "0123456789" ]
```

So the code would look like this:

- Set
`n`

to 0. - Set
`base`

to the number of symbols in the base. - For each digit,
- Set
`n`

to the result of the multiplication of`n`

and`base`

. - Get the offset of the digit in the array of symbols that make up the base.
- Set
`n`

to the result of the addition of`n`

and the offset.

- Set

Example Perl implementation:

```
my @syms = split //, "01234567890";
my %sym_offset = map { $syms[$_] => $_ } 0 .. $#syms;
my $s = "...";
my $n = 0;
for my $sym ( split //, $s ) {
my $offset = $sym_offset{ $sym };
$n = $n * @syms + $offset;
}
$s = $syms[ 0 ] if !length( $s );
say $n;
```

The opposite of this process can be taken to take a number and convert it to base. Instead of repeatedly multiplying, one would repeatedly divide, using the remainder as an index into the list of symbols that make up the base.

- Set
`base`

to the number of symbols in the base. - Set
`s`

to an empty string. - While
`n`

is greater than zero,- Find the remainder of
`n`

divided by`base`

. - Get the symbol found at the offset equal to the remainder.
- Prepend the symbol to
`s`

. - Set
`n`

to the result of the subtraction of the remainder from`n`

. - Set
`n`

to the result of the division of`n`

by`base`

.

- Find the remainder of
- If
`s`

is an empty string,- Set
`s`

to the first symbol.

- Set

Example Perl implementation:

```
my @syms = split //, "01234567890";
my %sym_offset = map { $syms[$_] => $_ } 0 .. $#syms;
my $n = ...;
my $s = "";
while ( $n ) {
my $offset = $n % @syms;
$s = $syms[ $offset ] . $s;
$n = ( $n - $offset ) / @syms;
}
say $n;
```

[ad_2]