问题
I'm trying to obtain the maximum value of a certain unsigned integer type without including any headers like <limits>
. So I thought I'd simply flip the bits of the unsigned integer value 0.
#include <iostream>
#include <limits>
int main()
{
std::cout << (~0U) << '\n'; // #1
std::cout << (std::numeric_limits< unsigned >::max()) << '\n'; // #2
return 0;
}
I'm not very experienced on the subtle differences between these. Which is why I'm asking if some unexpected behavior or some platform/architecture issues could occur by using the first method.
回答1:
... to obtain the maximum value of a certain unsigned integer type without including any headers
Simply assign the value -1
unsigned_type_of_choice max = -1;
Conversion of the -1
, which is an int
, to any unsigned type results in the value of number that is one greater than the largest value minus 1.
The following does not provide the maximum value of the destination type. It fails when the destination type range exceed the range of unsigned
, which is the type of ~0U
. @Christopher Oicles
// problem
unsigned_type_of_choice max_wannabe = ~0U;
回答2:
You shouldn't assign ~0U
to just any unsigned type, chux's answer already explains why.
For C++, with the following you can get the maximum possible value for all unsigned types.
template <typename T>
T max_for_unsigned_type() {
return ~(static_cast<T> (0));
}
You are negating a zero of your exact type. I use a verbose function name because it shouldn't be used for signed values. The problem is that for checking signedness the easiest way would be including an extra header, namely type_traits. This other answer then would be useful.
Usage:
max_for_unsigned_type<uint8_t> ();
max_for_unsigned_type<uint16_t> ();
max_for_unsigned_type<uint32_t> ();
max_for_unsigned_type<uint64_t> ();
max_for_unsigned_type<unsigned> ();
Values returned: (see test code here)
255
65535
4294967295
18446744073709551615
4294967295
Note: Doing it for signed types is much more difficult, see Programmatically determining max value of a signed integer type.
来源:https://stackoverflow.com/questions/39864070/obtaining-max-of-unsigned-integer-with-bitwise-not-on-zero-value