What is wcstoul in C?

The wcstoul function in C interprets a given wide string as an unsigned integral number of a specified base. All characters up to the first non-numeric character are converted to an unsigned long integer. The wcstoul function ignores any leading whitespace.

Note: The unsigned long data type can take on any value between 00 to (2321)(2^{32}-1).

The process is illustrated below:

Note: A wide string is comprised of characters from the Unicode character set.

To use the wcstoul function, you will need to include the <wchar.h> library in the program, as shown below:

#include <wchar.h>

The prototype of the wcstoul function is shown below:

unsigned long int wcstoul(const wchar_t *str, wchar_t **str_end, int base);

Parameters

The wcstoul function takes the following objects as parameters:

  • str: The wide string to be converted.
  • str_end: A pointer that references the characters after the last valid numeric character in str. This parameter may also be a null pointer.
  • base: The base of the integral value.

Note: The set of values for the base is {00,22,33,…,3535,3636}.

Return value

If the conversion is successful, the wcstoul function returns an unsigned long integer value; otherwise, it returns 00.

Example

The code below shows how the wcstoul function works in C:

#include <stdio.h>
#include <wchar.h>
int main() {
// initilaizing strings
wchar_t str[] = L"2021Educative22";
wchar_t* str_end;
unsigned long int result;
// converting string to long long int
result = wcstoul(str, &str_end, 10);
// output results
printf("The converted unsigned integral number is %lu.\n", result);
printf("The remaining string is \'%ls\'.", str_end);
return 0;
}

Explanation

First, the code initializes the wide string we want to convert. The ‘L’ identifier in line 7 informs the compiler that the Unicode character set is being used. The str_end pointer will contain the string that remains after conversion.

The wcstoul function in line 12 proceeds to convert the given wide string, “2021Educative22”, to an unsigned long integer. For this example, the decimal number system (base 1010) is used.

Since the first 44 characters (“2021”) represent valid numeric characters, the conversion is successful and the wcstoul function returns the value 20212021. The remaining string, “Educative22”, is stored at the location pointed to by str_end.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved