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);


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()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
    ptr = 0;// oops, I meant *ptr = 0

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q