strtol(), strtoll()

Convert a string into a long integer

Synopsis:

#include <stdlib.h>

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

long long strtoll( const char * ptr,
                   char ** endptr,
                   int base );

Arguments:

ptr
A pointer to the string to parse.
endptr
If this argument isn't NULL, the function stores in it a pointer to the first unrecognized character found in the string.
base
The base of the number being parsed:
  • If base is zero, the first characters after the optional sign determine the base used for the conversion. If the first characters are 0x or 0X the digits are treated as hexadecimal. If the first character is 0, the digits are treated as octal. Otherwise, the digits are treated as decimal.
  • If base isn't zero, it must have a value between 2 and 36. The letters a-z and A-Z represent the values 10 through 35. Only those letters whose designated values are less than base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The strtol() function converts the string pointed to by ptr to an object of type long int; strtoll() converts the string pointed to by ptr to an object of type long long.

These functions recognize strings that contain the following:

  • optional white space
  • an optional plus or minus sign
  • a sequence of digits and letters.

The conversion ends at the first unrecognized character. If endptr isn't NULL, a pointer to the unrecognized character is stored in the object endptr points to.

Returns:

The converted value.

If the correct value causes an overflow, the function will return either LONG_MAX||LONGLONG_MAX or LONG_MIN||LONGLONG_MIN depending to the sign, and errno will be set to ERANGE. If base is out of range, the function returns zero and sets errno to EINVAL.

Examples:

#include <stdlib.h>

int main( void )
  {
    long int v;

    v = strtol( "12345678", NULL, 10 );
    return EXIT_SUCCESS;
  }

Classification:

ANSI, POSIX 1003.1

Safety:  
Cancellation point No
Interrupt handler Yes
Signal handler Yes
Thread Yes

Last modified: 2013-12-23

comments powered by Disqus