C library - strtol() function



The C stdlib library strtol() function is used to convert a string to a long integer number according to the given base. which must be lies between 2 and 32 inclusive, or be the special value 0.

Syntax

Following is the C library syntax of the strtol() function −

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

Parameters

This function accepts following parameters −

  • str − It is a string to be converted into a long integer value.

  • endptr − It is a pointer to a charter pointer and used to store the pointer to the first character after the numeric value.

  • base − It represents the base of the number system(e.g., 10 for decimal and 16 for hexadecimal).

Return Value

This function returns the converted long integer value. If the input string is not a valid, it returns 0.

Example 1

In this example, we create a basic c program to demonstrate how to use the strtol() function.

#include <stdio.h>
#include <stdlib.h>

int main() {
   const char *str = "12345abc";
   char *endptr;
   long int num;

   // Convert the string to a long integer
   num = strtol(str, &endptr, 10);
   if (endptr == str) {
      printf("No digits were found.\n");
   } else if (*endptr != '\0') {
      printf("Invalid character: %c\n", *endptr);
   } else {
      printf("The number is: %ld\n", num);
   }
   return 0;
}

Output

Following is the output −

Invalid character: a

Example 2

The example below convert a decimal number string to a long decimal integer, using the strtol() function.

#include <stdio.h>
#include <stdlib.h>

int main() {
   const char *str = "12205";
   char *endptr;
   long int num;

   // Convert the string to a long integer
   num = strtol(str, &endptr, 10);
   
   //display the long integer number    
   printf("The number is: %ld\n", num);    
   return 0;
}

Output

Following is the output −

The number is: 12205

Example 3

ILet's create another example, we convert the number into the long hexadecimal number, using the strtol() function.

#include <stdio.h>
#include <stdlib.h>

int main() {
   const char *str = "2024 tutorialspoint";
   char *endptr;
   long int num;
   
   // Convert the string to a long integer
   num = strtol(str, &endptr, 16);
   
   //display the long hexadecimal integer number    
   printf("The hexadecimal number is: %ld\n", num);
   return 0;
}

Output

Following is the output −

The hexadecimal number is: 8228
Advertisements