5 /* strtoul( const char *, char * *, int )
7 This file is part of the Public Domain C Library (PDCLib).
8 Permission is granted to use, modify, and / or redistribute at will.
11 #include <_PDCLIB_int.h>
18 unsigned long int strtoul( const char * s, char ** endptr, int base )
22 const char * p = _PDCLIB_strtox_prelim( s, &sign, &base );
23 rc = _PDCLIB_strtox_main( &p, base, ULONG_MAX, ULONG_MAX / base, ULONG_MAX % base, &sign );
24 if ( endptr != NULL ) *endptr = ( p != NULL ) ? (char *) p : (char *) s;
25 return ( sign == '+' ) ? rc : -rc;
31 #include <_PDCLIB_test.h>
37 /* this, to base 36, overflows even a 256 bit integer */
38 char overflow[] = "-ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ_";
41 /* basic functionality */
42 TESTCASE( strtoul( "123", NULL, 10 ) == 123 );
43 /* proper detecting of default base 10 */
44 TESTCASE( strtoul( "123", NULL, 0 ) == 123 );
45 /* proper functioning to smaller base */
46 TESTCASE( strtoul( "14", NULL, 8 ) == 12 );
47 /* proper autodetecting of octal */
48 TESTCASE( strtoul( "014", NULL, 0 ) == 12 );
49 /* proper autodetecting of hexadecimal, lowercase 'x' */
50 TESTCASE( strtoul( "0xFF", NULL, 0 ) == 255 );
51 /* proper autodetecting of hexadecimal, uppercase 'X' */
52 TESTCASE( strtoul( "0XFF", NULL, 0 ) == 255 );
53 /* errno should still be 0 */
54 TESTCASE( errno == 0 );
55 /* overflowing subject sequence must still return proper endptr */
56 TESTCASE( strtoul( overflow, &endptr, 36 ) == ULONG_MAX );
57 TESTCASE( errno == ERANGE );
58 TESTCASE( ( endptr - overflow ) == 53 );
59 /* same for positive */
61 TESTCASE( strtoul( overflow + 1, &endptr, 36 ) == ULONG_MAX );
62 TESTCASE( errno == ERANGE );
63 TESTCASE( ( endptr - overflow ) == 53 );
64 /* testing skipping of leading whitespace */
65 TESTCASE( strtoul( " \n\v\t\f123", NULL, 0 ) == 123 );
66 /* testing conversion failure */
67 TESTCASE( strtoul( overflow, &endptr, 10 ) == 0 );
68 TESTCASE( endptr == overflow );
70 TESTCASE( strtoul( overflow, &endptr, 0 ) == 0 );
71 TESTCASE( endptr == overflow );