Is there any API to check if any number exceeds it's range?
My number is stored as string. char *ptr = "123456789"
API should do: int a = api(ptr, long)
if a==-1 suppose value exceeds.
Please note: We can't parse the string and check because it will automatically wrap it to the other side, and make it within the range.
开发者_开发技巧Thanks in advance
Please checkout strtol and strtoul.
See this example:
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
int main (int argc, char const* argv[])
{
char a[] = "123";
char c[] = "123134123412341234";
long b, d;
errno = 0;
b = strtol(a, NULL, 10);
if((b == LONG_MAX || b == LONG_MIN) && errno == ERANGE ){
printf("%s Out of range\n", a);
}
errno = 0;
d = strtol(c, NULL, 10);
if((d == LONG_MAX || d == LONG_MIN) && errno == ERANGE ){
printf("%s Out of range\n", c);
}
return 0;
}
Edits:
- Changed
int
tolong
forb
andd
. - Setting
errno
to0
before calling into c library. - Checking for
LONG_MIN
also for errors. - Changed the order for checks (according to comment below)
Well, you can still check. Just build up the number and check to see if the number indeed became bigger or smaller.
int i = 0; // pos indicator
int r = 0; // result
int c = 0; // check
while(ptr[i])
{
c = r;
r = r * 10 + (ptr[i++] - '0');
if(r < c)
print("overflow happened!\n");
}
Edit: Note that this won't work with unsigned datatypes as it's too easy to overflow far enough to still pass the check.
Just use strol() or strtoll() and check errno. For smaller datatypes you need to make a very simple function that compares against USHRT_MAX, UINT_MAX etc from limits.h.
man strol and man limits.h for more information.
精彩评论