w3resource

C strtol() function

C strtol() function - Convert a string to a long integer

Syntax strtol() function

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

The strtol() function is used to convert a character string to a long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. The parameter str points to a sequence of characters that can be interpreted as a numeric value of type long int.

Parameters strtol() function

Name Description Required /Optional
str Null-terminated string to convert. Required
endptr An output parameter, set to point to the character after the last interpreted character. Ignored, if NULL. Required
base Number base to use. Required

Return value from strtol()

  • Upon successful completion, the function returns the converted value.
  • Returns 0 if no conversion is possible.

Example: strtol() function

The following example shows the usage of strtol() function.

#include <stdlib.h>
#include <stdio.h>
 
int main(void)
{
   char *string, *stopstring;
   long result;
   int bs;
 
   string = "2334567765924932";
   printf("String = %s\n", string);
   for (bs = 2; bs <= 8; bs *= 2)
   {
      result = strtol(string, &stopstring, bs);
      printf("\nstrtol = %ld (base %d)\n", result, bs);
      printf("Stopped scan at %s\n", stopstring);
      }
}

Output:

String = 2334567765924932

strtol = 0 (base 2)
Stopped scan at 2334567765924932

strtol = 47 (base 4)
Stopped scan at 4567765924932

strtol = 326299637 (base 8)
Stopped scan at 924932

C Programming Code Editor:

Previous C Programming: C strtod()
Next C Programming: C strtoul()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/c-programming/stdlib/c-strtol.php