Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does UINT_MAX have all bits set to 1?

In C, the maximum value for an unsigned integer must be in the form1: 2N - 1.

Thus all value bits of the value UINT_MAX will be set to 1. There may be padding bits, whose values are unspecified.


1 (Quoted from: ISO/IEC 9899:201x 6.2.6.2 Integer types 1)
For unsigned integer types other than unsigned char, the bits of the object representation shall be divided into two groups: value bits and padding bits (there need not be any of the latter). If there are N value bits, each bit shall represent a different power of 2 between 1 and 2N−1 , so that objects of that type shall be capable of representing values from 0 to 2N−1 using a pure binary representation; this shall be known as the value representation. The values of any padding bits are unspecified.


No, not quite.

An unsigned type can consist of value bits and padding bits.

You are correct that the value bits will always be set to 1 for the maximum value, but the specific values of the padding bits is left to the implementation. So this means that UINT_MAX needs to be a Mersenne number. Other requirements state it can't be less than 65535.

C and C++ are equivalent in this respect.


You're correct to say that by the definition of conversions, -1 converted to unsigned int is guaranteed to be UINT_MAX. It hasn't anything to do with any bit patterns. If there was an implementation where UINT_MAX was 100, then -1 converted to unsigned int would be 100.

There are reasons why UINT_MAX cannot be 100: One because it must be ≥ 2^16-1, but that would allow UINT_MAX = 1,000,000. Second, because unsigned int must have a binary representation with some fixed number n of value bits, so UINT_MAX = 2^n - 1.

It is possible that INT_MAX = 2^31 - 1 and UINT_MAX = 2^31 - 1 (not 2^32 - 1 as it is usually). In that case -1 would have 32 bits set; -1 cast to unsigned int would be 2^31 - 1 and have only 31 bits set.