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);


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()

Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
    ptr = 0;// oops, I meant *ptr = 0

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q