Re: Converting large strings to numbers



"David Resnick" <lndresnick@xxxxxxxxx> writes:
> rou...@xxxxxxxxx wrote:
>> Without using errno, is there a portable way to detect if a string
>> number is not within the range 0 to 4294967295.
>>
>> Currently I am using strtoul. I can check the string for "-" as the
>> first character before calling strtoul, so I can figure out if the
>> value is less than 0.
>>
>> My issue arises when the number is greater than 4294967295 on
>> platforms where ULONG_MAX is 4294967295; in this case strtoul will
>> return ULONG_MAX and set errno to ERANGE. However, some platforms I
>> work on do not support errno. So there is no way for me to know
>> that the value was greater than 4294967295.
>>
>> Is there another way to do this ?
>
> Well, if strtoul returns ULONG_MAX, you could compare the string being
> converted to "4294967295". If it is NOT the same, you have overflowed.

Unless the string is "+4294967295", or "04294967295", or
"+0004294967295". That's if you use a "base" argument of 10; if you
set "base" to 0, a leading '0' implies octal, and you also have to
worry about "037777777777", "00037777777777", "0xffffffff",
"0X000FfFfFfFf", and so forth.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.



Relevant Pages

  • Re: Converting large strings to numbers
    ... is there a portable way to detect if a string ... >first character before calling strtoul, so I can figure out if the ... >ULONG_MAX and set errno to ERANGE. ...
    (comp.lang.c)
  • Re: Fwd: strdup(NULL) supposed to create SIGSEGV?
    ... insufficient memory is available, NULL is returned and errno is set to ENOMEM.) ... system calls on modern systems), it has some fairly complex logic for managing and caching memory provided by the kernel. ... a string is a sequence of non-nul characters followed by a nul ...
    (freebsd-hackers)
  • Re: Converting large strings to numbers
    ... >>ULONG_MAX and set errno to ERANGE. ... Ok as long as you mean convert the value to a string with, say, sprintf ... If the source number is all digits then strcmpof the ... > odd character sets, because of the C standard's specifi rules about the ...
    (comp.lang.c)
  • Re: Promoting unsigned long int to long int
    ... char *ptr = NULL; ... there are no problems or else if its unsigned int it should overflow. ... seperate function for size_t and parse the string. ... if (errno == ERANGE) ...
    (comp.lang.c)
  • Re: opening a file
    ... If used as a string rather than a number, ... yields the current value of the C "errno" ... might be meaningless. ... ref Returns a non-empty string if EXPR is a reference, ...
    (comp.lang.perl.misc)