in reply to
Opposite of strtol?
This one is longer than a one-liner. Let's call the stringification function from the gmp library.
First, make sure you have the gmp library and the headers for it installed, eg. if you have a debian linux system, install the libgmp3-dev package.
Then make a directory called Math-Tobase-1.0 and enter the following code to a file called Tobase.xs in it:
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include <gmp.h>
MODULE = Math::Tobase PACKAGE = Math::Tobase
SV *
tobase(radix, num)
int radix
long num
CODE:
ST(0) = sv_newmortal();
if (2 <= radix && radix <= 62 || -36 <= radix && radix <= -2)
+{
mpz_t big;
mpz_init_set_si(big, num);
if (mpz_sizeinbase(big, radix) <= 70) {
char buf[72];
mpz_get_str(buf, radix, big);
sv_setpv(ST(0), buf);
}
mpz_clear(big);
}
Then enter the following to a file called lib/Math/Tobase.pm under the Math-Tobase-1.0 directory (create the subdirectories):
package Math::Tobase;
require Exporter;
require DynaLoader;
our $VERSION = "1.00";
our @ISA = (Exporter::, DynaLoader::);
our @EXPORT = "tobase";
bootstrap Math::Tobase::;
1;
__END__
=head1 NAME
Math::Tobase - Convert integers to a string in any radix
=head1 SYNOPSIS
use Math::Tobase;
print tobase(16, 200), "\n"; # prints c8
=head1 DESCRIPTION
=over 4
=item tobase RADIX, INTEGER
Converts an integer to a string in any radix (number base),
returning a string.
The radix must be an integer between 2 and 62 or between -36 and -2,
inclusive.
If the magnitude of the radix is greater than 10 but at most 36,
lowercase letters a to z are used to indicate digits greater
than 9; however, if the radix is greater than 36
then digits between 10 and 35 are represented with uppercase,
and digits greater than 35 are represented with lowercase letters.
=back
=head1 INSTALLATION
This module requires the gmp (GNU MP) library,
which you can download from L<http://gmplib.org/>.
=cut
Then enter the following to the Makefile.PL file under the Math-Tobase-1.0 directory.
use ExtUtils::MakeMaker;
WriteMakefile(
NAME => "Math::Tobase",
VERSION_FROM => "lib/Math/Tobase.pm",
LIBS => ["-lgmp"],
);
Now compile the code with the command
perl Makefile.PL && make
If all is successful, you can install the module now and get a Math::Tobase module with a tobase function that does what you want.
Try it out before installing using the command
perl -I./lib -Iblib/arch -we 'use Math::Tobase; print tobase(13, 54),
+"\n";'
The output shall be 42.
Update 2011-03-18: see also Re: Module for 128-bit integer math? for a list of bigint modules. See also Re: Convert big number from decimal to hexadecimal where I reuse this code.
Update 2012-10-16: note to self (as I reference this code frequently): you may want to use XSLoader.