Fast functions to convert between number bases
This documentation refers to version 1.8.B59BrZX of Math::BaseCnv, which was released on Mon May 9 11:53:35:33 2011.
use Math::BaseCnv; # CoNVert 63 from base-10 (decimal) to base- 2 (binary ) $binary_63 = cnv( 63, 10, 2 ); # CoNVert 111111 from base- 2 (binary ) to base-16 (hex ) $hex_63 = cnv( 111111, 2, 16 ); # CoNVert 3F from base-16 (hex ) to base-10 (decimal) $decimal_63 = cnv( '3F', 16, 10 ); print "63 dec->bin $binary_63 bin->hex $hex_63 hex->dec $decimal_63\n";
BaseCnv provides a few simple functions for converting between arbitrary number bases. It is as fast as I currently know how to make it (of course relying only on the lovely Perl). If you would rather utilize an object syntax for number-base conversion, please see Ken Williams' <[email protected]> fine Math::BaseCalc module.
The reason I created BaseCnv was that I needed a simple way to convert quickly between the 3 number bases I use most (10, 16, && 64). It turned out that it was trivial to handle any arbitrary number base that is represented as characters. High-bit \s-1ASCII\s0 has proven somewhat problemmatic but at least BaseCnv can simply && realiably convert between any possible base between 2 && 64 (or 85). I'm happy with it && employ b64() in places I probably shouldn't now =).
CoNVert the number contained in $numb from its current number base ($from) into the result number base ($tobs).
When only $numb is provided as a parameter:
If $numb only contains valid decimal (base 10) digits, it will be converted to hexadecimal (base 16).
If $numb only contains valid hexadecimal (base 16) digits or begins with '0x', it will be it will be converted to decimal (base 10).
When only $numb && $from are provided as parameters:
cnv() assumes that $numb is already in decimal format && uses $from as the $tobs.
When all three parameters are provided:
The normal (&& most clear) usage of cnv() is to provide all three parameters where $numb is converted from $from base to $tobs.
cnv() is the only function that is exported from a normal 'use Math::BaseCnv;' command. The other functions below can be imported to local namespaces explicitly or with the following tags:
:all - every function described here :hex - only dec() && hex() :b64 - only b10() && b64() && b64sort() && cnv() :dig - only dig() && diginit() :sfc - only summ(), fact(), && choo()
A shortcut to convert the number given as a parameter ($b64n) from base 64 to decimal (base 10).
A shortcut to convert the number given as a parameter ($b10n) from decimal (base 10) to base 64.
A way to sort b64 strings as though they were decimal numbers.
A shortcut to convert the number given as a parameter ($b16n) from hexadecimal (base 16) to decimal (base 10).
A shortcut to convert the number given as a parameter ($b10n) from decimal (base 10) to hexadecimal (base 16).
Please read the \*(L"\s-1NOTES\s0\*(R" regarding hex().
Assign the new digit character list to be used in place of the default one. dig() can also alternately accept a string name matching one of the following predefined digit sets:
'bin' => ['0', '1'] 'oct' => ['0'..'7'] 'dec' => ['0'..'9'] 'hex' => ['0'..'9', 'a'..'f'] 'HEX' => ['0'..'9', 'A'..'F'] 'b62' => ['0'..'9', 'a'..'z', 'A'..'Z'] 'b64' => ['0'..'9', 'A'..'Z', 'a'..'z', '.', '_'] 'm64' => ['A'..'Z', 'a'..'z', '0'..'9', '+', '/'] # MIME::Base64 'iru' => ['A'..'Z', 'a'..'z', '0'..'9', '[', ']'] # IRCu 'url' => ['A'..'Z', 'a'..'z', '0'..'9', '-', '_'] # MIME::Base64::URLSafe 'rex' => ['A'..'Z', 'a'..'z', '0'..'9', '!', '-'] # RegEx 'id0' => ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] # ID 0 'id1' => ['A'..'Z', 'a'..'z', '0'..'9', '.', '_'] # ID 1 'xnt' => ['A'..'Z', 'a'..'z', '0'..'9', '.', '-'] # XML Nmtoken 'xid' => ['A'..'Z', 'a'..'z', '0'..'9', '_', ':'] # XML ID Name 'b85' => ['0'..'9', 'A'..'Z', 'a'..'z', '!', '#', # RFC 1924 for '$', '%', '&', '(', ')', '*', '+', '-', # IPv6 addrs ';', '<', '=', '>', '?', '@', '^', '_', # like in '`', '{', '|', '}', '~' ] # Math::Base85
If no \@newd list or digit set name is provided as a parameter, dig() returns the current character list. It's fine to have many more characters in your current digit set than will be used with your conversions (e.g., using dig('b64') works fine for any cnv() call with $from && $tobs params less than or equal to 64).
An example of a \@newd parameter for a specified alternate digit set for base 9 conversions is:
dig( [ qw( n a c h o z y u m ) ] );
Resets the used digit list to the initial default order of the predefined digit set: 'b64'. This is simply a shortcut for calling dig('b64') for reinitialization purposes.
A simple function to calculate a memoized BigInt summation of $numb down to 1.
A simple function to calculate a memoized BigInt factorial of $numb. A simple function to calculate a memoized BigInt function of $ennn choose $emmm.
The Perl builtin hex() function takes a hex string as a parameter && returns the decimal value (FromBase = 16, ToBase = 10) but this notation seems counter-intuitive to me since a simple reading of the code suggests that a hex() function will turn your parameter into hexadecimal (i.e., It sounds like Perl's hex() will hexify your parameter but it does not.) so I've decided (maybe foolishly) to invert the notation for my similar functions since it makes more sense to me this way && will be easier to remember (I've had to lookup hex() in the Camel book many times already which was part of the impetus for this module... as well as the gut reaction that sprintf() is not a proper natural inverse function for hex()).
This means that my b64() function takes a decimal number as a parameter && returns the base64 equivalent (FromBase = 10, ToBase = 64) && my b10() function takes a base64 number (string) && returns the decimal value (FromBase = 64, ToBase = 10). My hex() function overloads Perl's builtin version with this opposite behavior so my dec() function behaves like Perl's normal hex() function. I know it's confusing && maybe bad form of me to do this but I like it so much better this way that I'd rather go against the grain.
Please think of my dec() && hex() functions as meaning decify && hexify. Also the pronunciation of dec() is 'dess' (!'deck' which would be the inverse of 'ink' which \*(-- && ++ already do so well). After reading the informative Perl module etiquette guidelines, I now appreciate the need to export as little as is necessary by default. So to be responsible, I have limited BaseCnv exporting to only cnv() under normal circumstances. Please specify the other functions you'd like to import into your namespace or use the tags described above in the cnv() section like:
'use Math::BaseCnv qw(:all !:hex);'
Error checking is minimal.
This module does not handle fractional number inputs because I like using the dot (.) character as a standard base64 digit since it makes for clean filenames.
summ(), fact(), && choo() are general Math function utilities which are unrelated to number-base conversion but I didn't feel like making another separate module just for them so they snuck in here.
I hope you find Math::BaseCnv useful. Please feel free to e-mail me any suggestions or coding tips or notes of appreciation (\*(L"app-ree-see-ay-shun\*(R"). Thank you. \s-1TTFN\s0.
Revision history for Perl extension Math::BaseCnv:
* updated 'url' digit set to URLSafe to resolve \s-1HTTPS://RT\s0.CPAN.Org/Ticket/Display.html?id=60125 * updated license copyright years (already had GPLv3)
* bumped minor version number so they'll keep ascending (without \s-1PT\s0 comprehension)
* added Math::BigInt code for >64-bit number-base conversions * added a bunch more DigitSets: IRCu, \s-1URL\s0, RegEx, identifier variants, \s-1XML\s0 Nmtoken, && \s-1XML\s0 \s-1ID\s0 Name
* added Test::Pod(::Coverage)? tests && \s-1PREREQ\s0 entries * added b85 for IPv6, gen'd \s-1META\s0.yml (w/ newline before \s-1EOF\s0), up'd minor ver
* added b64sort() && put pod at bottom
* testing Make as primary and BuildPL backup (needing rename for dot)
* testing just using Module::Build instead of MakeMaker * fixed test 12 which was failing on \s-1AMD64\s0 * added Build.PL to pkg
* removed 128 digit-set since some hi-bit chars cause probs on Win32 * made bin/cnv only executable to go in \s-1EXE_FILES\s0 * made Math::BaseCalc a link in pod && updated License
* tidied \s-1POD\s0 && upped minor version number since \s-1CPAN\s0 can't read \s-1PTVR\s0
* added test for div-by-zero error in choo() * added summ()
* snuck in fact() && choo()
* changed test.pl to hopefully pass MSWin32-x86-multi-thread
* broke apart \s-1CHANGES\s0 to descend chronologically * made dec() auto uppercase param since dec(a) was returning 36 instead of 10
* put cnv in bin/ as \s-1EXE_FILES\s0
* testing new e auto-gen \s-1MANIFEST\s0(.SKIP)?
* updated \s-1POD\s0
* normalized base spelling
* added \s-1ABSTRACT\s0 section to WriteMakeFile() * changed synopsis example * updated all \s-1POD\s0 indenting
* removed indenting from \s-1POD\s0 \s-1NAME\s0 field
* updated package to coincide with Time::Fields release
* synchronized \s-1POD\s0 with \s-1README\s0 documentation using new e utility * templatized package compilation * fixed boundary bugs
* first version (&& my first Perl module... yay!) put on \s-1CPAN\s0
* reworked interface from shell utility to package
* original version
Please run:
`perl -MCPAN -e "install Math::BaseCnv"`
or uncompress the package && run:
`perl Makefile.PL; make; make test; make install` or if you don't have `make` but Module::Build is installed `perl Build.PL; perl Build; perl Build test; perl Build install`
Most source code should be Free! Code I have lawful authority over is && shall be! Copyright:(c) 2003-2011, Pip Stuart. Copyleft : This software is licensed under the \s-1GNU\s0 General Public License (version 3). Please consult the Free Software Foundation (\s-1HTTP://FSF\s0.Org)
for important information about your freedom.
Pip Stuart <[email protected]>