What is strtol in C?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.


Syntax

Here is how it is defined in C:

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

Functions used to define it in C:

  • str: A pointer to the string that is to be converted to a long integer.
  • endptr: A pointer used by strtol, which points to the first non-integer character signaled to stop conversion.
  • base: The base of the number being converted. It must be between 2 and 32, inclusive, or be a special value 0.

Note: If the base is 0, the number is assumed to be a decimal, unless, the converted number starts with O (for Octal) or Ox (for hexadecimal).


Examples

1. String to long integer conversion

A simple conversion from a string, to a long integer,​ works like this:

#include <stdlib.h> // the library required to use strtol
int main() {
char str[50] = "2020111224234234";
char *remaining;
long answer;
answer = strtol(str, &remaining, 10);
printf("The converted long integer is %ld\n", answer);
return 0;
}

2. String with whitespace and characters to long integer

This example highlights how strtol ignores whitespaces at the start, and also stores the rest of the string in remaining.

#include <stdlib.h> // the library required to use strtol
int main() {
char str[50] = " 90908752 rest of the string";
char *remaining;
long answer;
answer = strtol(str, &remaining, 10);
printf("The converted long integer is %ld\n", answer);
printf("The string part was: %s. ", remaining);
return 0;
}

3. String to hexadecimal conversion

Here’s how to convert a string to hexadecimal. Note that the base argument strtol is set to 16, which is the base for hexadecimals.

#include <stdlib.h> // the library required to use strtol
int main() {
char str[50] = "0x85fa4b";
char *remaining;
long answer;
answer = strtol(str, &remaining, 16);
printf("The converted hexadecimal is %lx\n", answer); // %lx is the format for hexadecimals
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved