NAME
Math::Base::Convert - very fast base to base conversion
SYNOPSIS
As a function
use Math::Base::Convert qw( :all )use Math::Base::Convert qw(cnvcnvabscnvprebasemap# commentsbin base 2 0,1dna base 4 lower case dnaDNA base 4 upper case DNAoct base 8 octaldec base 10 decimalhex base 16 lower case hexHEX base 16 upper case HEXb62 base 62b64 base 64 month:C:12 day:V:31m64 base 64 0-63 from MIME::Base64iru base 64 P10 protocol - IRCu daemonurl base 64 url with no %2B %2F expansion of + - /rex base 64 regular expression variantid0 base 64 IDentifier style 0id1 base 64 IDentifier style 1xnt base 64 XML Name Tokens (Nmtoken)xid base 64 XML identifiers (Name)b85 base 85 RFC 1924 for IPv6 addressesascii base 96 7 bit printible 0x20 - 0x7F);my $converted = cnv($number,optionalFROM,optionalTO);my $basemap = basmap(base);
As a method:
use Math::Base::Convert;use Math::Base::Convert qw(:base);my $bc = new Math::Base::Convert(optionalFROM,optionalTO);my $converted = $bc->cnv($number);my $basemap = $bc->basemap(base);
DESCRIPTION
This module provides fast functions and methods to convert between arbitrary number bases from 2 (binary) thru 65535.
This module is pure Perl, has no external dependencies, and is backward compatible with old versions of Perl 5.
PREFERRED USE
Setting up the conversion parameters, context and error checking consume a significant portion of the execution time of a single base conversion. These operations are performed each time cnv is called as a function.
Using method calls eliminates a large portion of this overhead and will improve performance for repetitive conversions. See the benchmarks sub-directory in this distribution.
BUILT IN NUMBER SETS
Number set variants courtesy of the authors of Math::Base:Cnv and Math::BaseConvert.
The functions below return a reference to an array
$arrayref = function;bin => ['0', '1'] # binarydna => ['a','t','c','g'] # lc dnaDNA => ['A','T','C','G'], {default} # uc DNAoct => ['0'..'7'] # octaldec => ['0'..'9'] # decimalhex => ['0'..'9', 'a'..'f'] # lc hexHEX => ['0'..'9', 'A'..'F'] {default} # uc HEXb62 => ['0'..'9', 'a'..'z', 'A'..'Z'] # base 62b64 => ['0'..'9', 'A'..'Z', 'a'..'z', '.', '_'] # m:C:12 d:V:31m64 => ['A'..'Z', 'a'..'z', '0'..'9', '+', '/'] # MIMI::Base64iru => ['A'..'Z', 'a'..'z', '0'..'9', '[', ']'] # P10 - IRCuurl => ['A'..'Z', 'a'..'z', '0'..'9', '*', '-'] # url no %2B %2Frex => ['A'..'Z', 'a'..'z', '0'..'9', '!', '-'] # regex variantid0 => ['A'..'Z', 'a'..'z', '0'..'9', '_', '-'] # ID 0id1 => ['A'..'Z', 'a'..'z', '0'..'9', '.', '_'] # ID 1xnt => ['A'..'Z', 'a'..'z', '0'..'9', '.', '-'] # XML (Nmtoken)xid => ['A'..'Z', 'a'..'z', '0'..'9', '_', ':'] # XML (Name)b85 => ['0'..'9', 'A'..'Z', 'a'..'z', '!', '#', # RFC 1924'$', '%', '&', '(', ')', '*', '+', '-',';', '<', '=', '>', '?', '@', '^', '_','', '{', '|', '}', '~']An arbitrary base 96 composed of printable 7 bit asciifrom 0x20 (space) through 0x7F (tilde ~)ascii => [' ','!','"','#','$','%','&',"'",'(',')','*','+',',','-','.','/','0','1','2','3','4','5','6','7','8','9',':',';','<','=','>','?','@','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','[','\',']','^','_','`','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','{','|','}','~']NOTE: Clean text with =~ s/\s+/ /; before applying to ascii
USAGE
- •
-
$converted= cnv($number,[from],[to])SCALAR context: array context covered later in this document.
To preserve similarity to other similar base conversion modules, cnv returns the converted number string with SIGN if both the input and output base strings are in known signed set of bases in this module.
In the case of binary, octal, hex, all leading base designator strings such as '0b','0', '0x' are automatically stripped from the input. Base designator strings are NOT applied to the output.
The context of base FROM and TO is optional and flexible.
Unconditional conversion from decimal to HEX [upper case]
$converted = cnv($number);Example conversion from octal to default HEX [upper case] with different context for the 'octal' designator.
base as a number$converted = cnv($number,8);base as a function (imported)$converted = cnv($number,oct);base as text$converted = convbase($number,'oct');Conversion to/from arbitrary bases i.e.
$converted = cnv($number); # dec -> hex (default)$converted = cnv($number,oct); # oct to HEX$converted = cnv($number,10,HEX); # dec to uc HEX$converted = cnv($number,10,hex); # dec to lc hex$converted = cnv($number,dec,hex);# samepointer notation$converted = cnv($number, oct => dec);$converted = cnv($number,10 => 23); # dec to base23$converted = cnv($number,23 => 5); # b23 to base5etc...
- •
-
$bc= new Math::Base::Convert([from],[to]);This method has the same usage and syntax for FROM and TO as cnv above.
Setup for unconditional conversion from HEX to decimal
$bc = new Math::Base::Convert();Example conversion from octal to decimal
base number$bc = new Math::Base::Convert(8);base function (imported)$bc = new Math::Base::Convert(oct);base text$bc = new Math::Base::Convert('oct')The number conversion for any of the above:
NOTE: iterative conversions using a method pointer are ALWAYS faster than calling cnv as a function.
$converted = $bc->cnv($number);
- •
-
$converted= cnvpre($number,[from],[to])Same as cnv except that base descriptor PREfixes are applied to binary, octal, and hexadecimal output strings.
- •
-
$converted= cnvabs($number,[from],[to])Same as cnv except that the ABSolute value of the number string is returned without SIGN is returned. i.e. just the raw string.
- •
-
($sign,$prefix,$string) = cnv($number,[$from,[$to]])
- •
-
($sign,$prefix,$string) = cnv($number,[$from,[$to]])
- •
-
($sign,$prefix,$string) = cnv($number,[$from,[$to]])
ARRAY context:
All three functions return the same items in array context.
sign the sign of the input number stringprefix the prefix which would be applied to outputstring the raw output string
- •
-
$basemap= basemap(base);
- •
-
$basemap=$bc->basemap(base);This function / method returns a pointer to a hash that maps the keys of a base to its numeric value for base conversion. It accepts base in any of the forms described for cnv.
The return basemap includes upper and lower case variants of the the number base in cases such as hex where upper and lower case a..f, A..F map to the same numeric value for base conversion.
i.e. $hex_ptr = {0 => 0,1 => 1,2 => 2,3 => 3,4 => 4,5 => 5,6 => 6,7 => 7,8 => 8,9 => 9,A => 10,B => 11,C => 12,D => 13,E => 14,F => 15,a => 10,b => 11,c => 12,d => 13,e => 14,f => 15};
BENCHMARKS
Math::Base::Convert includes 2 development and one real world benchmark sequences included in the test suite. Benchmark results for a 500mhz system can be found in the 'benchmarks' source directory.
make test BENCHMARK=1
Provides comparison data for bi-directional conversion of an ascending series of number strings in all base powers. The test sequence contains number strings that go from a a single 32 bit register to several. Tested bases are: (note: b32, b128, b256 not useful and are for testing only)
base 2 4 8 16 32 64 85 128 256bin, dna, oct, hex, b32, b64, b85, b128, b256
Conversions are performed FROM all bases TO decimal and are repeated in the opposing direction FROM decimal TO all bases.
Benchmark 1 results indicate the Math::Base::Convert typically runs significantly faster ( 10x to 100x) than Math::BigInt based implementations used in similar modules.
make test BENCHMARK=2
Provides comparison data for the frontend and backend converters in Math::Base::Convert's CalcPP and Shortcuts packages, and Math::Bigint conversions if it is present on the system under test.
make test BENCHMARK=3
Checks the relative timing of short and long number string conversions. FROM a base number to n*32 bit register and TO a base number from an n*32 bit register set.
i.e. strings that convert to and from 1, 2, 3... etc.. 32 bit registers
DEPENDENCIES
noneMath::BigInt is conditionally used inthe test suite but is not a requirement
EXPORT_OK
Conditional EXPORT functions
cnvcnvabscnvprebasemapbinoctdecheXHEXb62b64m64iruurlrexid0id1xntxidb85ascii
EXPORT_TAGS
Conditional EXPORT function groups
:all => all of above:base => all except 'cnv,cnvabs,cnvpre'
ACKNOWLEDGEMENTS
This module was inspired by Math::BaseConvert maintained by Shane Warden <[email protected]> and forked from Math::BaseCnv, both authored by Pip Stuart <[email protected]>
AUTHOR
Michael Robinton, <[email protected]>
COPYRIGHT
Copyright 2012-2015, Michael Robinton
This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.