Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we convert a string to int for very large integer values?

Tags:

c

linux

char

int

I have used the function atoi to convert character strings to int and it's working fine but when I gave

num = atoi (argv[1]) ;

// argv contain 4294967295 maximun value of 32 bit integer

it's giving me 2147483647 answer which is basically half of 4294967295

i guess that its because of difference of bytes in char and int. Can any one explain whats happening to bits and bytes and how to fix it or convert it to int

like image 439
mainajaved Avatar asked Oct 08 '11 15:10

mainajaved


2 Answers

You've run into the maximum value of an integer. Since atoi returns an int, it is limited to the size of an integer on your machine. It looks like your machine uses 32-bit ints.

In case you missed it (it's easy to miss), 2147483647 = (2 ^ 31) - 1. Remember that ints can be negative, and the leftmost bit is the sign bit in that case. That's why you see the number being "limited" to 2147483647.

Try defining num as unsigned int instead of int, and use strtoul instead of atoi.

like image 116
Zach Rattner Avatar answered Sep 25 '22 06:09

Zach Rattner


Use strtoul instead of atoi. The latter results in undefined behavior if the value overflows int, which is what happens in your case.

like image 24
R.. GitHub STOP HELPING ICE Avatar answered Sep 24 '22 06:09

R.. GitHub STOP HELPING ICE