In this tutorial, you will learn about string conversion function C strtoul() that converts the string to unsigned long.

c strtoul() - string conversion function

strtoul() is defined under general utilities library header stdlib.h. Therefore we should include <stdlib.h> in our program.

#include<stdlib.h>

Function prototype of C strtoul()


aunsigned long strtoul( const char *sPtr, char **endPtr, int base );

where,

sPtr = string that contains an unsigned integral number

endPtr = pointer set by the function to the first character in sPtr after integer value

base = base of the value being converted that can be 0 or any value between 2 and 36

Return Value


This function returns 0 if it’s unable to convert any portion of its first argument to unsigned long int value.

C program to illustrated the concept of string conversion function strtoul()

//C string conversion function strtoul

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

int main()
{
   //initializing string pointer
   const char *sPtr = "40 student are pass";

   unsigned long int n; //variable to store converted string
   char *endPtr; //char type pointer

   n = strtoul( sPtr, &endPtr, 0 );

   printf("Original String: \"%s\"\n", sPtr);
   printf("\nUnsigned long int Value: %lu"
          "\nRemaining string part: %s\n", n, endPtr);

   return 0;
}

Output

c strtoul function

Explanation

In the above example, the converted unsigned long int value is stored in n whereas, remaining part of the sPtr after conversion is assigned to endPtr.

The base value 0 indicates the value to be converted can be in octal, decimal or hexadecimal format.