sscanf - %li query
Michael Meissner
meissner@linux.vnet.ibm.com
Fri Jan 2 17:07:00 GMT 2009
On Fri, Jan 02, 2009 at 11:35:32AM +0530, Rahul wrote:
> Hello all,
>
> Please help me with this example.
> #include <stdio.h>
> int main()
> {
> signed long v;
> printf("sizeof(long) = %d\n", sizeof(long));
> v = 0xFFFFFFFF;
> printf("v-li = %li; v-lx = %lx\n", v, v);
> sscanf("0xFFFFFFFF","%li", &v);
> printf("v-li = %li; v-lx = %lx\n", v, v);
> sscanf("0xFFFFFFFF","%lx", &v);
> printf("v-li = %li; v-lx = %lx\n", v, v);
> return 0;
> }
> Got the following output for the above code with gcc version 3.2.3.
> sizeof(long) = 4
> v-li = -1; v-lx = ffffffff
> v-li = 2147483647; v-lx = 7fffffff
> v-li = -1; v-lx = ffffffff
> Why are values different when "%li" is used with 'sscanf'. Am I
> missing something here or can this be a bug?
> Request your guidance if this is not the correct place to post this query.
The glibc group is probably more appropriate to post questions about the
library, but I can answer it here, since it is related to the ISO C standard.
In the C99 standard, sscanf function (chapter 7.19.6.7) is defined in terms of
doing the same thing as fscanf (chapter 7.19.6.2). Under fscanf, %li is defined
in terms of calling the strtol function, while %lx is defined in terms of
calling the strtoul function with a base of 16.
Both strtol and strtoul are defined in chapter 7.20.1.4. Strtol will check
whether the value is in the range LONG_MIN and LONG_MAX while strtoul will
check whether the value is in the range ULONG_MIN and ULONG_MAX. If the value
is out of range, the appropriate min/max is returned and errno is set to
ERANGE. The value 0xffffffff is too large to fit in LONG_MAX, so errno is set
to ERANGE and LONG_MAX (on a 32-bit system, 2147483647 or 0x7fffffff) is
returned. On the other hand, 0xffffffff does fit in the range for strtoul.
--
Michael Meissner, IBM
4 Technology Place Drive, MS 2203A, Westford, MA, 01886, USA
meissner@linux.vnet.ibm.com
More information about the Gcc-help
mailing list