您的位置:首页 > Web前端

safe convert string to integer function

2018-03-07 10:44 399 查看
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include <errno.h>
#include <assert.h>

/* Convert string to integer
*
* Parses a base-10 number from the given string.  Checks that the
* string is not blank, contains only numerical characters, and is
* within the range of INT32_MIN to INT32_MAX.  If the validation is
* successful the result is stored in *value; otherwise *value is
* unchanged and errno is set appropriately.
*
* \return true if the number parsed successfully, false on error
*/
static inline bool
safe_strtoint(const char *str, int32_t *value)
{
long ret;
char *end;

assert(str != NULL);

errno = 0;
ret = strtol(str, &end, 10);
if (errno != 0) {
return false;
} else if (end == str || *end != '\0') {
errno = EINVAL;
return false;
}

if ((long)((int32_t)ret) != ret) {
errno = ERANGE;
return false;
}
*value = (int32_t)ret;

return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: