strtoul Function

Convert string to unsigned long integer value.

Include

<stdlib.h>

Prototype

unsigned long int strtoul( const char * restrict nptr, char ** restrict endptr, int base);

Arguments

nptr
the string to attempt to convert
endptr
pointer to the remainder of the string that was not converted
base
The base of the conversion

Return Value

The converted value, or 0 if the conversion could not be performed.

Remarks

The strtoul function attempts to convert the first part of the string pointed to by nptr to a unsigned long integer value.

Any initial whitespace characters in the string are skipped. The following characters representing the integer are assumed to be in a radix specified by the base argument. Conversion stops once an unrecognized character is encountered in the string. If the correct converted value is out of range, the value of the macro ERANGE is stored in errno.

If the value of base is zero, the characters representing the integer can be in any valid C constant form (i.e., in decimal, octal, or hexadecimal), but any integer suffix is ignored. If the value of base is between 2 and 36 (inclusive), the expected form of the integer characters is a sequence of letters and digits representing an integer with the radix specified by base, optionally preceded by a plus or minus sign, but again, the integer suffix is ignored. The letters from a (or A) through z (or Z) are ascribed the values 10 through 35; only letters and digits whose ascribed values are less than that of base are permitted. If the value of base is 16, the characters 0x or 0X may optionally precede the sequence of letters and digits, following the sign if present.

When using MPLAB XC8, the function will set errno to EINVAL and return 0 if base is invalid.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
{ 
  char * string = "-1234abcd";
  char * final;
  unsigned long result;
  
  result = strtoul(string, &final, 10);
  printf("The integer conversion of the string \"%s\" is %lud; final string part is \"%s\"\n", string, result, final);
}

Example Output

The integer conversion of the string "-1234abcd" is 4294966062d; final string part is "abcd"