[ILUG] sprintf formatting question
Jimmy O'Regan
joregan at gmail.com
Wed Aug 20 14:06:26 IST 2008
2008/8/20 Phil <philb at vodafone.ie>:
>
> Hi,
>
> I thought this one was obvious but seemingly not. I have a value, in excess
> of 2^32 that I want to print out using perl (ancient RedHat 8.0 on 32 bit).
> The output should be padded to 10 characters.
>
> First test works fine:
> my $foo = 3188931580; # > 2147483648
> print sprintf("%10u\n", $foo);
>
> Second test, fails due to overflow
> my $foo = 5188931580; # > 4294967295
> print sprintf("%10u\n", $foo);
>
> (actually prints out 4294967295)
>
>
> My understanding was that a prefix of "L" or "ll" would indicate to sprintf
> that the value is a "long long" so that any of the following should work:
>
> print sprintf("%10lld\n", $foo); # Prints -1
> print sprintf("%10llu\n", $foo); # Print 4294967295
> print sprintf("%10Ld\n", $foo); # Prints -1
> print sprintf("%10Lu\n", $foo); # Prints 4294967295
>
> Have I misunderstood the sprintf syntax or is this a limitation of perl on
> 32 bit?
>
RTFM :)
For numeric conversions, you can specify the size to interpret the
number as using l , h , V , q, L , or ll . For integer conversions (d
u o x X b i D U O ), numbers are usually assumed to be whatever the
default integer size is on your platform (usually 32 or 64 bits), but
you can override this to use instead one of the standard C types, as
supported by the compiler used to build Perl:
l interpret integer as C type "long" or "unsigned long"
h interpret integer as C type "short" or "unsigned short"
q, L or ll interpret integer as C type "long long", "unsigned long long".
or "quads" (typically 64-bit integers)
The last will produce errors if Perl does not understand "quads" in
your installation. (This requires that either the platform natively
supports quads or Perl was specifically compiled to support quads.)
You can find out whether your Perl supports quads via Config:
use Config;
($Config{use64bitint} eq 'define' || $Config{longsize} >= 8) &&
print "quads\n";
More information about the ILUG
mailing list