C Data Type Functions - C strtol

Converts string to long integer.

long int strtol(const char *str , char **endptr , int base );

The string str is converted to a long integer (type long int).

Any initial whitespace characters are skipped.

The number may consist of an optional sign and a string of digits.

Conversion stops when the first unrecognized character is reached.

If the base (radix) argument is zero, then the conversion is dependent on the first two characters.

If the first character is a digit from 1 to 9, then it is base 10.

If the first digit is a zero and the second digit is a digit from 1 to 7, then it is base 8 (octal).

If the first digit is a zero and the second character is an x or X, then it is base 16 (hexadecimal).

If the base argument is from 2 to 36, then that base (radix) is used and any characters that fall outside of that base definition are considered unconvertible.

For base 11 to 36, the characters A to Z (or a to z) are used.

If the base is 16, then the characters 0x or 0X may precede the number.


long int strtol (const char* str, char** endptr, int base);


This function has the following parameter.

C-string beginning with the representation of an integral number.
Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence.


returns the converted integral number as a long int value.

If no valid conversion could be performed, a zero value is returned 0L.


#include <stdio.h> /* printf */
#include <stdlib.h> /* strtol */
//from   w  w  w.ja v  a  2 s  . c om
int main (){
  char szNumbers[] = "2123 60c0c0 -110111010011010 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers,&pEnd,10);
  li2 = strtol (pEnd,&pEnd,16);
  li3 = strtol (pEnd,&pEnd,2);
  li4 = strtol (pEnd,NULL,0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;


The code above generates the following result.

Example 2

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
 //from  ww w . j a va  2 s.  c  om
int main(void){
    const char *p = "10 20000000000000000000000000 30 -40";
    printf("Parsing '%s':\n", p);
    char *end;
    for (long i = strtol(p, &end, 10);
         p != end;
         i = strtol(p, &end, 10)){
        printf("'%.*s' -> ", (int)(end-p), p);
        p = end;
        if (errno == ERANGE){
            printf("range error, got ");
            errno = 0;
        printf("%ld\n", i);

The code above generates the following result.