C Data Type Functions - C strtoul






Converts a string to an unsigned long.

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

The string str is converted to an unsigned long integer (type unsigned long int).

Any initial whitespace characters are skipped.

The number may consist of an optional sign and a string of digits.

Conversion stops when the first unrecognized character is reached.

If the base (radix) argument is zero, then the conversion is dependent on the first two characters.

If the first character is a digit from 1 to 9, then it is base 10.

If the first digit is a zero and the second digit is a digit from 1 to 7, then it is base 8 (octal).

If the first digit is a zero and the second character is an x or X, then it is base 16 (hexadecimal).

If the base argument is from 2 to 36, then that base (radix) is used and any characters that fall outside of that base definition are considered unconvertible.

For base 11 to 36, the characters A to Z (or a to z) are used.

If the base is 16, then the characters 0x or 0X may precede the number.





Prototype

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

Parameter

This function has the following parameter.

str
C-string containing the representation of an integral number.
endptr
Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
base
Numerical base (radix) that determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence.

Return

On success, the function returns the converted integral number as an unsigned long int value.

If no valid conversion could be performed, a zero value is returned.

If the value read is out of the range of representable values by an unsigned long int, the function returns ULONG_MAX (defined in <climits>), and errno is set to ERANGE.

Example


#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* strtoul */
//from w  w  w  .j  av  a 2 s  . c  o  m
int main (){
  char buffer [256];
  unsigned long ul;
  printf ("Enter an unsigned number: ");
  fgets (buffer, 256, stdin);
  ul = strtoul (buffer, NULL, 0);
  printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
  return 0;
} 

The code above generates the following result.





Example 2


#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
 /*  ww w  .  j a  v a  2s .c om*/
int main(void){
    const char *p = "10 200000123412312312312300000000 30 40";
    printf("Parsing '%s':\n", p);
    char *end;
    for (unsigned long i = strtoul(p, &end, 10);
         p != end;
         i = strtoul(p, &end, 10)){
        printf("'%.*s' -> ", (int)(end-p), p);
        p = end;
        if (errno == ERANGE){
            printf("range error, got ");
            errno = 0;
        }
        printf("%lu\n", i);
    }
}

The code above generates the following result.