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__
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.
Update 2013-11-19: for more XS examples, see Re: Perl XS.
|