Making a List, Checking it 0b10 Times...
Beyond Hex and Octal
It's sort of easy to convert between decimal, hexadecimal, and octal in Perl. sprintf
can produce decimal, hexadecimal, octal, or binary digit strings, and the oct
built-in can read those strings back into numbers. For example, to convert from hex to binary strings, we might do the following:
1: | my $hex = '99'; |
This is a little inconsistent, but fast and easy. Unfortunately, sometimes we need to work with really weird digit sets. Fortunately, Number::Nary makes these really easy to work with. For example, if we need to convert from sexagesimal to trinary (presumably because we are writing a Star Trek script) we can just create routines using Number::Nary like this:
1: | use Number::Nary |
Now we have four routines for converting between our numbering systems. Given the number 102012012 in trinary, we can easily convert it to sexagesimal:
1: | my $trinary = '102012012'; |
Neat, but is it ever practical? Yes! For one thing, it can be used to fix numbers into weird character sets. I've used it to cram several large numbers into email addresses by using the valid email address characters as a digit set. There's also Jesse Vincent's Number::RecordLocator, which "encodes integers into a short and easy to read and pronounce locator strings." Using Number::Nary, we can re-implement that module in about four lines:
1: | use Number::Nary -codec_pair => { |
Number::Nary is slower than sprintf
and oct
are, but since they can only handle a few different digit sets, they're not always going to solve the problem at hand. Having Number::Nary in the wings when you need it can be a real time-saver.
Finally, here's a quick bit of Christmas spirit:
1: | use Number::Nary 0.107 -codec_pair => { |
See Also
UDCode - to determine if a set of digits will produce unambiguous strings
Math::BaseCalc - another take on the problem (but I don't recommend it)