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

前端 未结 4 1019
隐瞒了意图╮
隐瞒了意图╮ 2021-01-12 14:11

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]) ;

/         


        
相关标签:
4条回答
  • 2021-01-12 14:43

    You can use strtoull for very long numbers.

    unsigned long long int strtoull(const char *nptr, char **endptr,
                                           int base);
    

    Compile with C99 support -std=c99 or provide the defines in man strtoull to get the definition.

    0 讨论(0)
  • 2021-01-12 14:48

    If you want to handle seriously very large numbers then you need a library like GMP.

    GMP stands for GNU Multiple Precision and it is a BigNum library, which means it has code to handle integers bigger than 32 bits or 64 bits. It can handle as many bits as you have RAM.

    To convert a string into an integer you would use the GMP function mpz_set_str()

    0 讨论(0)
  • 2021-01-12 14:54

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

    0 讨论(0)
  • 2021-01-12 14:59

    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.

    0 讨论(0)
提交回复
热议问题