strtoul() in C – Syntax, Use and Example

Write a C program to input string representation of integer and convert string to unsigned long using strtoul() library function. How to convert string to unsigned long int using strtoul() library function in C programming?

strtoul() library function

strtoul() function is used to convert string representation of integer to unsigned long int type. It is defined in stdlib.h header file.

Syntax of strtoul() function

unsigned long int strtoul(const char* str, char** endPtr, int base);
  • It accepts a pointer to constant character str i.e. string representation of integer.
  • endPtr is a pointer to char pointer. On successful conversion endPtr points to first character after number otherwise is a NULL pointer.
  • base is base of integer to convert i.e. 2 if str is a binary string or 10 if it is a decimal string.
  • On success function returns converted integer as unsigned long int type and set endPtr to point to character after first number. On failure it returns 0 and set endPtr to NULL.

Note: The function efficiently handles underflows and overflows. It return ULONG_MAX on overflow and 1 on underflow.

Also see how to find maximum and minimum limit of a data type?

Example program to use strtoul() function

/**
 * C program to convert string to unsigned long int using strtoul() library function.
 */

#include <stdio.h>
#include <stdlib.h>     // Used for strtoul()


int main()
{
    char number[30];
    char* endPtr;

    unsigned long int bigNumber;
    int base;


    /* Input string representation of number from user. */
    printf("Enter any number: ");
    gets(number);


    printf("Enter base: ");
    scanf("%d", &base);


    /* Convert string representation of number to unsigned long */
    bigNumber = strtoul(number, &endPtr, base);


    /* endPtr points to NULL for failed conversions */
    if(*endPtr)
        printf("Unable to convert '%s' to base %d.", number, base);
    else
        printf("Converted unsigned long int = %lu\n", bigNumber);


    return 0;
}

Note: %lu format specifier is used to print unsigned long int type.
Check list of all format specifiers in C programming.

Output

Enter any number: 2018
Enter base: 10
Converted unsigned long int = 2018

Enter any number: 01001
Enter base: 2
Converted unsigned long int = 9

Enter any number: 056
Enter base: 8
Converted unsigned long int = 46

Enter any number: 2018
Enter base: 10
Converted unsigned long int = 2018

Enter any number: de
Enter base: 1
Unable to convert 'de' to base 1.

Enter any number: de
Enter base: 16
Converted unsigned long int = 222

Enter any number: 999999999999999999999999999
Enter base: 10
Converted unsigned long int = 4294967295

Enter any number: -99999999999999999999999999
Enter base: 10
Converted unsigned long int = 1

Enter any number: 0
Enter base: 0
Converted unsigned long int = 0

Enter any number: de
Enter base: 10
Unable to convert 'de' to base 10.

Happy coding 😉