Skip to content

Instantly share code, notes, and snippets.

@qingl97
Last active August 29, 2015 14:18
Show Gist options
  • Save qingl97/f6fa5eb7eafe78b6ea57 to your computer and use it in GitHub Desktop.
Save qingl97/f6fa5eb7eafe78b6ea57 to your computer and use it in GitHub Desktop.
Convert string to integer C

Alternative to atoi() there is better way with using strtol():

Defined in header <stdlib.h>

long strtol( const char *str, char **str_end, int base ); (until C99)
long strtol( const char *restrict str, char **restrict str_end, int base ); (since C99)
long long strtoll( const char *restrict str, char **restrict str_end, int base ); (since C99)

The call atoi(str) shall be equivalent to: (int) strtol(str, (char **)NULL, 10) except that the handling of errors may differ. For atoi(), if the value cannot be represented(not in the format below), the behavior is undefined.

  • (optional) plus or minus sign
  • (optional) prefix (0) indicating octal base (applies only when the base is 8 or ​0​)
  • (optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or ​0​)
  • a sequence of digits

For If the str is empty or does not have the expected form, no conversion is performed, and (if str\_end is not NULL) the value of str is stored in the object pointed to by str_end.

See ref:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment