unsigned long int strtoul(const char *str,char **endptr, int base). i do not understand the base
When I run the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
char stringnumber[]="2002200345345345";
char *ptr_end;
long answer;
answer=strtoul(stringnumber,&ptr_end,10);
printf("the unsigned number is : %lu \n",answer);
return 0;
}
instead of getting "2002200345345345" this number i am getting:
unsigned number is: 4294967295
The function strtoul
will return ULONG_MAX
if the converted value is not representable as an unsigned long
.
You appear to be using a platform on which ULONG_MAX
is defined as 4,294,967,295
, which means that unsigned long
is 32 bits wide on your platform.
You can determine whether a range error occurred in strtoul
by checking whether that function set errno
to ERANGE
.
I suggest that you change your code to the following, so that it does extra validation:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int main()
{
char stringnumber[] = "2002200345345345";
char *ptr_end;
long answer;
//set errno to 0, so that we can later check whether it
//was modified by "strtoul"
errno = 0;
//attempt to convert string to integer
answer = strtoul( stringnumber, &ptr_end, 10 );
//check for conversion failure
if ( ptr_end == stringnumber )
{
printf( "conversion failure!\n" );
exit( EXIT_FAILURE );
}
//check for range error
if ( errno == ERANGE )
{
printf( "out of range error!\n" );
exit( EXIT_FAILURE );
}
//conversion was successful, so print the result
printf( "the unsigned number is : %lu \n", answer );
return 0;
}
This program has the following output on 64-bit Microsoft Windows (on which unsigned long
is 32 bits wide):
out of range error!
On 64-bit Linux (on which unsigned long
is 64 bits wide), it has the following output:
the unsigned number is : 2002200345345345
Instead of converting the number to an unsigned long
, you may want to consider converting it to an unsigned long long
instead. This type is guaranteed to be at least 64 bits wide and able to represent numbers up to at least 18,446,744,073,709,551,615
on all platforms. If you want to use unsigned long long
, you should use the function strtoull
instead.