aplonis has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to tell Math::BigInt that I want to preserve leading zeros?

I'm playing around with it for converting binary data to Radix87 and the truncation of occasional leading zeros throws a wrench into the works.

Replies are listed 'Best First'.
Re: Math::BigInt and Leading Zeros
by ides (Deacon) on May 04, 2005 at 12:48 UTC
    If your numbers are a fixed length, you can avoid having to edit the CPAN module and just use sprintf() to re-fill the leading zeros. Just another idea...

    Frank Wiles <frank@wiles.org>
    http://www.wiles.org

      sprintf doesn't quite work - it can only handle whatever the underlying perl library handles natively:

      $ perl5.8.6 -MMath::BigInt -e '$i = Math::BigInt->new("123_456_789_000 +_000"); printf "%025d\n", $i' -000000000000000000000001
      The next best thing I can think of is:
      $ perl5.8.6 -MMath::BigInt -e '$i = Math::BigInt->new("123_456_789_000 +_000"); $s = $i->bstr(); $s = '0' x (25 - length $s) . $s; print $s,$ +/' 0000000000123456789000000
      Note that this does the right thing if the string is already longer than you want, e.g.:
      $ perl5.8.6 -MMath::BigInt -e '$i = Math::BigInt->new("123_456_789_000 +_000"); $s = $i->bstr(); $s = '0' x (10 - length $s) . $s; print $s,$ +/' 123456789000000
      Hope that helps.

        The underlying perl library natively handles strings fine - just change '%25d' to '%25s':

        zen% perl -MMath::BigInt -e '$i = Math::BigInt->new("123_456_789_000 +_000"); printf "%025s\n", $i' 0000000000123456789000000 zen%

        Hugo

Re: Math::BigInt and Leading Zeros
by sh1tn (Priest) on May 04, 2005 at 12:40 UTC
    From the source of the package - leading zeroes are stripped.
    In the 'private' (_split) method:
    sub _split { ... $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g ... }
    So you may want to re-write the substitution to:
    ... $x =~ s/^\s*([-]?)(0*[0-9])/$1$2/g ...
    If this is acceptable at all.