Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Big Integers

Tags:

c++

flex-lexer

I am a writing a lexer as part of a compiler project and I need to detect if an integer is larger than what can fit in a int so I can print an error. Is there a C++ standard library for big integers that could fit this purpose?

like image 776
Eburetto Avatar asked Dec 02 '22 08:12

Eburetto


2 Answers

The Standard C library functions for converting number strings to integers are supposed to detect numbers which are out of range, and set errno to ERANGE to indicate the problem. See here

like image 121
Sol Avatar answered Dec 09 '22 11:12

Sol


You could probably use libgmp. However, I think for your purpose, it's just unnecessary.

If you, for example, parse your numbers to 32-bit unsigned int, you

  1. parse the first at most 9 decimal numbers (that's floor(32*log(2)/log(10)). If you haven't more, the number is OK.
  2. take the next digit. If the number you got / 10 is not equal to the number from the previous step, the number is bad.
  3. if you have more digits (eg. more than 9+1), the number is bad.
  4. else the number is good.

Be sure to skip any leading zeros etc.

like image 39
jpalecek Avatar answered Dec 09 '22 11:12

jpalecek