I want to be able to check if a number (initially Integer) after an operation would fit into Integer again, and if it does not, either jump to an exception or maybe there is some function that does it, like if isInteger() then ...
I do not want to convert to String and then to Integer and checking the length.
Why I need it? There is a variable (Integer) that keeps update interval, which is doubled every time the request to server fails (no network, whatever). So I want to turn off automatic updates when interval reaches the maximum possible Integer value, which is 2,147,483,647
Ive look for possible answers and it seems that everywhere people use String datatype to check for some conditions on the number, but i do not want to use intermediate datatypes
I'm going to attempt here to describe a variety of ways to solve your specific problem, and some more general problems of this nature.
The most general way to deal with overflow is to let the compiler write the code for you. Enable the overflow checking option and an exception will be raised if you perform an operation whose result does not fit into the data type range.
From the documentation:
The $Q directive controls the generation of overflow checking code. In the {$Q+} state, certain integer arithmetic operations (+, -, *, Abs, Sqr, Succ, Pred, Inc, and Dec) are checked for overflow. The code for each of these integer arithmetic operations is followed by additional code that verifies that the result is within the supported range. If an overflow check fails, an EIntOverflow exception is raised (or the program is terminated if exception handling is not enabled).
So if you wish to trap such a condition you can enable overflow checking and catch the EIntOverflow
exception.
That will work in full generality. However let us consider a more specific scenario. Suppose that you have a positive integer that you are incrementing by a positive value. Let us say your counter is count
, and your increment is incr
. You are trying to detect when
count + incr > MaxInt
Rearrange the inequality like this:
count > MaxInt - incr
You can simply test that inequality before attempting the increment operation.
In fact your specific case is even simpler than that. You are doubling the value rather than incrementing using addition. So simply check whether or not
count <= MaxInt div 2
Yet another option would be to take base 2 logarithms of the quantities. This would convert your doubling process into increment by 1. In which case all you are actually doing is counting up to 31! And converting back to a true interval is performed with 1 shl count
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments