w3resource

C strtoul() function

C strtoul() function - Convert a string to an unsigned long

Syntax strtoul() function

unsigned long int strtoul(const char *str, char **endptr, int base)

The strtoul() function is used to convert a character string to an unsigned long integer value. The parameter str points to a sequence of characters that can be interpreted as a numeric value of type unsigned long int.

Parameters strtoul() function

Name Description Required /Optional
str Null-terminated string to convert. Required
endptr Pointer to character that stops scan. Required
base Number base to use. Required

Return value from strtoul()

This function returns the converted integral number as a long int value. If no valid conversion could be performed, a zero value is returned.

  • Upon successful completion, these functions shall return the converted value, if any.
  • Returns 0 if base has an invalid value (less than 0, 1, or greater than 36)

Example: strtoul() function

The following example shows the usage of strtoul() function.

#include <stdio.h>
#include <stdlib.h>
 
#define BASE2 2
#define BASE4 4
 
int main(void)
{
   char *string, *stopstring;
   unsigned long ul;
 
   string = "1000e12 e";
   printf("Original string = %s\n", string);
   ul = strtoul(string, &stopstring, BASE2);
   printf("strtoul = %ld (base %d)\n", ul, BASE2);
   printf("Stopped scan at %s\n\n", stopstring);
   string = "10000000e12 e";
   printf("Original string = %s\n", string);
   ul = strtoul(string, &stopstring, BASE2);
   printf("strtoul = %ld (base %d)\n", ul, BASE4);
   printf("Stopped scan at %s\n\n", stopstring);
} 

Output:

Original string = 1000e12 e
strtoul = 8 (base 2)
Stopped scan at e12 e

Original string = 10000000e12 e
strtoul = 128 (base 4)
Stopped scan at e12 e

C Programming Code Editor:

Previous C Programming: C strtol()
Next C Programming: C calloc()



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/stdlib/c-strtoul.php