strtoul
P.J. Plauger
uunet!plauger!pjp
Thu Mar 25 10:37:29 PST 1993
Fred Tydeman asks:
> Assuming that unsigned long int is 32-bits wide, what are the return
> values (in base 16) and errno for the following:
I have annotated his examples along the right margin.
returns:
> strtoul( " 100000000", NULL, 16 ); ULONG_MAX set errno
> strtoul( " FFFFFFFF", NULL, 16 ); FFFFFFFF
> strtoul( " FFFFFFFE", NULL, 16 ); FFFFFFFE
> strtoul( " 80000001", NULL, 16 ); 80000001
> strtoul( " 80000000", NULL, 16 ); 80000000
> strtoul( " 7FFFFFFF", NULL, 16 ); 7FFFFFFF
> strtoul( " 1", NULL, 16 ); 00000001
> strtoul( " 0", NULL, 16 ); 00000000
> strtoul( " -1", NULL, 16 ); FFFFFFFF
> strtoul( " -7FFFFFFF", NULL, 16 ); 80000001
> strtoul( " -80000000", NULL, 16 ); 80000000
> strtoul( " -80000001", NULL, 16 ); 7FFFFFFF
> strtoul( " -FFFFFFFE", NULL, 16 ); 00000002
> strtoul( " -FFFFFFFF", NULL, 16 ); 00000001
> strtoul( "-100000000", NULL, 16 ); ULONG_MAX set errno
> I do not see a definition of negative of an unsigned
> long. It seems to me that the unsigned must be converted to signed,
> then the negation done, then converted back to unsigned.
The negative of an unsigned long follows from its required arithmetic
properties, plus the nature of the representation. For X-Y to
equal X+(-Y), the rules of twos complement arithmetic must obtain,
except that there is no overflow. The correct answer is the low
order N bits of the arithmetic result. No need to convert to
signed.
For further enlightenment, X3J11 has formed a response to
Defect Report #006, submitted by Walter J. Murray,
on the same subject:
The relevant citations are the ones supplied by you from subclause
7.10.1.6:
o If the subject sequence begins with a minus sign, the value
resulting from the conversion is negated.
o If the correct value is outside the range of representable values,
ULONG_MAX is returned, and the value of the macro ERANGE
is stored in errno.
The Committee believes that there is only one sensible interpretation
of a subject sequence with a minus sign: If the subject sequence (neglecting
the possible minus sign) is outside the range [0, ULONG_MAX],
then the range error is reported. Otherwise, the value is negated
(as an unsigned long int).
> What is the range of representable values for unsigned long? Is it
> [0..ULONG_MAX], [-ULONG_MAX..ULONG_MAX], everything is representable
> modulo ULONG_MAX+1, or something else?
The range is [0, ULONG_MAX-1]
This is my own unofficial interpretation. I cannot speak for WG14
or for SC22.
P.J. Plauger
More information about the Numeric-interest
mailing list