'Equivalent to atol() for numbers over long type (C language)

Is there a way to use atol() for numbers in strings bigger than the long type can store ?

c


Solution 1:[1]

For numbers outside the range of type long, you can use these standard functions defined in <stdlib.h>:

  • long long atoll(const char *s);
  • unsigned long long atoull(const char *s);
  • long long strtoll(const char *s, char **endp, int base);
  • unsigned long long strtoull(const char *s, char **endp, int base);

Using the strxxx versions is recommended to detect and handle overflow and invalid input.

For even larger numbers, you can use double or long double types, but the precision on the parsed value will be limited by the internal representation of these types, which have a much larger range and on most systems can also represent infinities:

  • double strtod(const char *s, char **endp);
  • long double strtold(const char *s, char **endp);

For more precision and/or integer range, you can use a bignum package such as the GNU multiple precision arithmetic library, GNU mpc, GNU mpfr or the LibBF used in QuickJS.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1