1

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

Pianissimo
  • 36
  • 4
  • 6
    There's `atoll` for `long long`, though `strtoll` is better. Nothing else is standard, because types longer than `long long` aren't standard. Note that `long long` is not necessarily any longer than `long`. – Nate Eldredge Apr 30 '22 at 22:26
  • 2
    Sounds like you need a bignum library. – Maarten Bodewes Apr 30 '22 at 22:29
  • 3
    You shouldn't be using `atoi()`/`atol()` at all. They provide *zero error checking* and will happily return `0` for `atoi ("my cow");` without any indication an error has occurred. Instead for values of 64-bit or less, `strtol()` or `strtoll()` or their unsigned counterparts. Otherwise you can either use in-exact floating point conversions like `strtod()` or you need a big-numbers library. – David C. Rankin Apr 30 '22 at 22:42
  • 1
    [Why shouldn't I use atoi()?](https://stackoverflow.com/q/17710018/995714) – phuclv May 01 '22 at 02:18

1 Answers1

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • but `double` or `long double` may have less precision than `long`. And they still have finite range – phuclv May 01 '22 at 01:37
  • @phuclv: `double` and `long double` do not have finite range, when IEEE-754 is used. They can represent values from −∞ to +∞. There is merely a large gap between the largest representable finite value and the next larger representable value. – Eric Postpischil May 01 '22 at 02:08
  • *a large gap*... by an measure, that can hardly be reduced even with bignums :) – chqrlie May 01 '22 at 12:08