I wanted a way to convert numbers into a different base (if thats the correct term - I'm no mathematician), where that base is determined by an array. The following works, but I'd like to know if it can be made shorter. It seems rather long for something so simple. Anyone feel like having a go?
I'll admit that this exercise is really nothing more than a silly vanity project for my website, to give me URLs somewhat similar to tinyurl.com, where numeric ids in a database will be converted to and from alphanumeric strings. Eg. http://mysite/?123 becomes http://mysite/?1Z or more interestingly http://mysite/?1000000 becomes http://mysite/?4c92
All efforts appreciated.#!/usr/bin/perl -w use strict; my @alphanum = (0 .. 9, "a" .. "z", "A" .. "Z"); my $divisor = scalar @alphanum; #my $enc = &enc(1_000); #my $dec = &dec($enc); #print "$enc $dec\n"; for (my $x=0; $x<10_000; $x++) { print "$x -> " . &enc($x) . "\n"; } exit 0; sub dec { my $num = shift; # strip leading 0's $num =~ s/$0+//g; my ($y, $result) = (0, 0); foreach (split(//, reverse($num))) { my $found = 0; foreach my $item (@alphanum) { if ($item eq $_) { last; } $found++; } my $temp = $found * ($divisor ** $y); $result += $temp; $y++; } return $result; } sub reduce { return (int($_[0] / $divisor), $_[0] % $divisor); } sub enc { my $num = shift; my $end = ""; my ($a, $b) = reduce($num); $end = $alphanum[$b] . $end; until ($a < $divisor) { ($a, $b) = reduce($a); $end = $alphanum[$b] . $end; } $end = $alphanum[$a] . $end unless $a == 0; return $end; }
In reply to convert numbers to a different (arbitrary) base by hostyle
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |