Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sprintf 64 test

8 views
Skip to first unread message

Leopold Toetsch

unread,
Oct 14, 2006, 6:38:08 PM10/14/06
to perl6-i...@perl.org, perl5-...@perl.org
Folks,

Either perl 5 or libc is wrong (or my testcase is bogus, or the standard ...):

$ perl -e'printf("!%03.2d!\n", 1)'
!001!

$ cc -Wall sprintf.c -o sprintf && ./sprintf '%03.2d' 1 # [1]
! 01!

Parrot is currently following the 'official' aka libc behavior and is
returning the latter result [2].

Not that I really need that, but the test is complaining ...

leo

[1]
$ cat sprintf.c
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *arg;
char fmt[256];

int i;
if (argc != 3) {
printf("usage: ./sprintf fmt int_arg\n");
return (1);
}
arg = argv[2];
i = atoi(arg);
sprintf(fmt, "!%s!\n", argv[1]);
printf(fmt, i);
return 0;
}

[2]
$ cat spf.pasm
new P1, .ResizablePMCArray
push P1, 1
sprintf S0, "!%03.2d!\n", P1
print S0
end
$ ./parrot spf.pasm
! 01!

SADAHIRO Tomoyuki

unread,
Oct 14, 2006, 8:56:11 PM10/14/06
to Leopold Toetsch, perl6-i...@perl.org, perl5-...@perl.org

On Sun, 15 Oct 2006 00:38:08 +0200, Leopold Toetsch wrote

> Folks,
>
> Either perl 5 or libc is wrong (or my testcase is bogus, or the standard ...):
>
> $ perl -e'printf("!%03.2d!\n", 1)'
> !001!
>
> $ cc -Wall sprintf.c -o sprintf && ./sprintf '%03.2d' 1 # [1]
> ! 01!
>
> Parrot is currently following the 'official' aka libc behavior and is
> returning the latter result [2].

I think the standard specifies the 0 flag in %d should be ignored
when a precision is given. (However what I referred is JIS X 3010,
that is the Japanese translation from ISO/IEC 9899, but not ANSI).

I found it online, cf. http://man.he.net/man3/sprintf

0 specifying zero padding.
(..snip..)
If a precision is given with a numeric conversion
(d, i, o, u, i, x, and X), the 0 flag is ignored.

I think then printf("!%03.2d!\n", 1) should put out
the same string as one from printf("!%3.2d!\n", 1),
that is ! 01!

P.S. Another suspicious behavior of perl5's (s?)printf is
the following case: when a precision is negative (given through *).

printf("!%3.*s!\n", -1, "ab"); # should be like printf("!%3s!\n", "ab");
printf("!%3.*s!\n", 0, "ab");
printf("!%3.*s!\n", 1, "ab");

I think they should print

! ab!
! !
! a!

but perl5 does

! !
! !
! a!

Regards,
SADAHIRO Tomoyuki


Rafael Garcia-Suarez

unread,
Oct 16, 2006, 5:26:27 AM10/16/06
to perl5-...@perl.org
SADAHIRO Tomoyuki wrote:
> Hi,
>
> here a patch against perl-current@29020, named sprintf.patch.gz,
> is attached. This patch includes 3 code changes:
>
> 1. to nullify 0 flag in integer conversions when precision is given
> 2. to ignore space after a plus sign as a sign for a nonnegative number
> 3. to make a negative precision through * working as if the precision
> is omitted
>
> and changes of pod and tests, too.

Thanks, applied as change #29025.

0 new messages