# printf vs. big numbers

#### Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

•  Subject
• Author
• Posted on

What does one need to do to make this not blow up when \$k reaches 10?
\$ perl -wle 'for \$k(10){for(qw/b d lld ld Ld o u x/){printf
"%%\$_\t%\$_\n",10**\$k}}'
%b    11111111111111111111111111111111
%d    -1
%lld    -1
%ld    -1
%Ld    -1
%o    37777777777
%u    4294967295
%x    ffffffff

## Re: printf vs. big numbers

j> What does one need to do to make this not blow up when \$k reaches 10?
j> \$ perl -wle 'for \$k(10){for(qw/b d lld ld Ld o u x/){printf
"%%\$_\t%\$_\n",10**\$k}}'
j> %b    11111111111111111111111111111111
j> %d    -1
j> %lld    -1
j> %ld    -1
j> %Ld    -1
j> %o    37777777777
j> %u    4294967295
j> %x    ffffffff

perl -wle 'for \$k(10){for(qw/f g b d lld ld Ld o u x/){printf
"%%\$_\t%\$_\n",10**\$k}}'
%f    10000000000.000000
%g    1e+10
%b    1001010100000010111110010000000000
%d    10000000000
%lld    10000000000
%ld    10000000000
%Ld    10000000000
%o    112402762000
%u    10000000000
%x    2540be400

get a 64 bit machine!

perl overflows integers to floats and you are seeing that. notice i
added f and g formats. try those. printing an integer format of a too
large float is going to generate nonsense since there aren't enough bits
to convert the number correctly.

uri

## Re: printf vs. big numbers

On 09/20/2009 08:31 PM, jidanni@jidanni.org wrote:

The answer is to use bigint and to not use printf:

#!/usr/bin/perl
use strict;
use warnings;
use bigint qw/lib GMP/;

my (\$k,\$m);

for \$k (10) {
for \$m (qw/copy as_bin as_hex/) {
print "\$m: ", (10**\$k)->\$m, "\n";
}
}