How can I find the maximal integer value of an unknown type? Is there something more efficient than this:
template<class T>
T test(T i) {
if (((T)-1) > 0)
return -1;
T max_neg = ~(1 << ((sizeof(T)*8)-1));
T all_ones = -1;
T max_pos = all_ones & max_neg;
return max_pos;
}
If the first bit is 1 and all the other 31 bits are 0 then the number will be the maximum negative number . Integer. MAX_VALUE represents the maximum positive integer value that can be represented in 32 bits (i.e., 2147483647 ).
The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.
To get max value you actually have to calculate the sum of 2^n with n from 0 to 31 or simpler 2^32 - 1 and you'll get '4294967295' as max for unsigned int, one less than anticipated. Now do the same with 2^31 - 1 for signed int and you'll get 2,147,483,647 .
Use std::numeric_limits<T>::max()
. Since C++11, this function is constexpr
and thus evaluated at compile-time.
std::numeric_limits<T>::max()
is a good starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With