CLOUD 1015
CLOUD 1015

Reputation: 13

C: How do I convert a string to int which will be in long int format

I want to convert a string "12341234123412341234" to int, but when I use atoi it returns -1

char n[100] = "12341234123412341234";
printf("%d",atoi(n));

returns -1

if i use %ld or %lld it returns a junk value

char n[100] = "12341234123412341234";
printf("%lld",atoi(n)); //even if i use %ld it returns the same value

returns 4294967295

Upvotes: 0

Views: 219

Answers (2)

HAL9000
HAL9000

Reputation: 2188

atoi returns an int. The largest value that can have on a typical 32 or 64 bit architecture (with 32 bit int) is 2147483647. So whatever atoi would return in your case depends on the implementation, but we can be fairly sure that it wont be 12341234123412341234

Trying to tell printf that the parameter passed to it is a long or a long long using "%ld" or "%lld" cannot work either. It doesn't change the fact that atoi returns an int, and that is what get passed to printf. So in addition to that the return value from atoi is not what you want, you are lying about the datatype passed to printf. Nothing good comes out of lying to your computer. Besides long and long long can typically not hold the value 12341234123412341234 either.

An integer type of uint64_t can hold values from 0 to 18446744073709551615 which should work in your case. Typically uint64_t is the same as unsigned long long, and you can use strtoull to parse that:

const char *n = "12341234123412341234";
char *end;
unsigned long long v = strtoull(n, &end, 10);
printf ("%llu\n", v);

Naturally, if the string n comes from untrusted sources, a robust program should inspect the pointer end for parse errors.

See man strtoull for more info.

You should also check out INT_MAX and ULLONG_MAX (and other *_MAX) for your architecture.

Upvotes: 1

dbush
dbush

Reputation: 225737

The function you want is strtol:

char n[100] = "12341234123412341234";
printf("%llu", strtoull(n, NULL, 10));

Upvotes: 3

Related Questions