关于atoi的实现

时间:2023-03-08 16:17:17

一、关于atoi atol的实现

__BEGIN_NAMESPACE_STD
__extern_inline double
__NTH (atof (__const char *__nptr))
{
return strtod (__nptr, (char **) NULL);
}
__extern_inline int
__NTH (atoi (__const char *__nptr))
{
return (int) strtol (__nptr, (char **) NULL, 10);
}
__extern_inline long int
__NTH (atol (__const char *__nptr))
{
return strtol (__nptr, (char **) NULL, 10);
}
__END_NAMESPACE_STD

From /usr/include/stdlib.h

参考:

atoi: Convert string to integer

二、strtol

Parses the C-string str interpreting its content as an integral number of the specified base, which is returned as a long int value. If endptr is not a null pointer, the function also sets the value of endptr to point to the first character after the number.处理C语言字符串,将其内容作为一个某个特定base/进位制的整数,返回的是一个 long int值。如果参数endptr不是一个空指针,函数也会将enptr的值指向number的第一个字符。

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax that depends on the base parameter, and interprets them as a numerical value. Finally, a pointer to the first character following the integer representation in str is stored in the object pointed by endptr.这个函数首先会discard掉开头的(尽可能多的)whitespace/空格,直到第一个 非-空格出现。然后,从这个(非-空格)字符开始,取(尽可能多的、且符合base参数规则的)字符 并将这个字符解释为一个数值。

If the value of base is zero, the syntax expected is similar to that of integer constants, which is formed by a succession of:

An optional sign character (+ or -)
An optional prefix indicating octal or hexadecimal base ("0" or "0x"/"0X" respectively)
A sequence of decimal digits (if no base prefix was specified) or either octal or hexadecimal digits if a specific prefix is present

If the base value is between 2 and 36, the format expected for the integral number is a succession of any of the valid digits and/or letters needed to represent integers of the specified radix (starting from '0' and up to 'z'/'Z' for radix 36). The sequence may optionally be preceded by a sign (either + or -) and, if base is 16, an optional "0x" or "0X" prefix.

If the first sequence of non-whitespace characters in str is not a valid integral number as defined above, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

For locales other than the "C" locale, additional subject sequence forms may be accepted.

strtol