in reply to bin2dec for big numbers

More Perlish techniques will be welcomed.

I don't mean to rain on your parade, but I think that one of the most Perlish techniques is to see whether anyone else has already written it... enter Math::BaseCalc.

#! /usr/bin/perl -w use strict; use Math::BaseCalc; my $bin = Math::BaseCalc->new( digits => [0,1] ); my $num; for $num( @ARGV ) { print "$num base 2 = ", $bin->from_base($num), " base 10\n"; }

When run, the above produces:

% ./b2d 1110010101011101111011110110101010111 1110010101011101111011110110101010111 base 2 = 123140435287 base 10

And you can be sure that the module has received extensive testing...

Update: you're right, if the number to be converted is big enough, it will use scientific notation. You learn something every day.

- another intruder with the mooring in the heart of the Perl

Replies are listed 'Best First'.
Re^2: bin2dec for big numbers (use Math::BaseCalc)
by spurperl (Priest) on Jan 18, 2005 at 12:07 UTC
    I looked into Math::BaseCalc, and I might be missing something, but it doesn't look to answer my requirements.

    It seems that Math::BaseCalc is also limited in the size of numbers it can handle. Try giving a very long string to it, say 200 binary digits. It returns results in scientific notation (...e+...), and those of course are far from being precise. It's probably limited to 32 or 64 bits (depends on what Perl's int is)

    My bin2dec, OTOH, always returns an exact decimal number.

    So, am I missing something ?

Re^2: bin2dec for big numbers (use Math::BaseCalc)
by spurperl (Priest) on Jan 18, 2005 at 11:40 UTC
    Thanks for this, I will keep it in mind for the future.

    The original implementation was in C++ so BaseCalc was out of the question - I just translated it to Perl to demonstrate the tecnique to fellow monks and ask about clever usage of Perl's operators to make the code less C++ like.