Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the max value of unknown integer type

Tags:

c++

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;
}
like image 490
zenpoy Avatar asked Jul 08 '13 08:07

zenpoy


People also ask

How do you find the maximum value of an integer?

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 ).

What is the largest number that can be represented by the type uint32_t?

The UInt32 value type represents unsigned integers with values ranging from 0 to 4,294,967,295.

How do you find the maximum value of Int32?

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 .


2 Answers

Use std::numeric_limits<T>::max(). Since C++11, this function is constexpr and thus evaluated at compile-time.

like image 68
mavam Avatar answered Oct 30 '22 13:10

mavam


std::numeric_limits<T>::max() is a good starting point.

like image 20
Bathsheba Avatar answered Oct 30 '22 14:10

Bathsheba