C Reference function strtol()

This function of stdlib will convert a string to long integer.

Usage of strtol():

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

Parameters:

C string str interpreting its content as an integral number of the specified base, which is returned as a long int value. If endptr is not a null pointer, the function also sets the value pointed by endptr to point to the first character after the number. White-spaces are discarded until the first non-whitespace character is found.

Return value:

The function returns the converted floating point number as a long int value, if successful.
If no valid conversion could be performed then an zero value is returned.
If the value is out of range then LONG_MAX or LONG_MIN is returned.

Source code example of strtol():


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

int main ()
{
	char buffer[] = "2008 40a0b0 -1101110100110111100110 0x5abfff";
	char * ptr_end;
	long int li1, li2, li3, li4;

	li1 = strtol (buffer,&ptr_end,10);
	li2 = strtol (ptr_end,&ptr_end,16);
	li3 = strtol (ptr_end,&ptr_end,2);
	li4 = strtol (ptr_end,NULL,0);

	printf ("In decimals: %ld, %ld, %ld, %ld.\n", li1, li2, li3, li4);

	return 0;
}

Output of the strtol example program above:


	In decimals: 2008, 4235440, -3624422 , 5947391
This entry was posted in C Reference stdlib.h Functions. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

Comments are closed.