user1097048
user1097048

Reputation:

Does UINT_MAX have all bits set to 1?

This question is asked before but I am still confused.

I know that

unsigned int a = -1;

would be UINT_MAX. But it is not because all bits of -1 is set. C11 says

if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type

So lets say UINT_MAX is 100 (I know it should be greater then 2^16-1 but lets ignore this for now)

unsigned int a = -1; // will be
unsigned int a = -1 + UINT_MAX + 1; // 100 = UINT_MAX  

Standard only says UINT_MAX >= 2^16-1. But does it say anywhere it should be 2^n-1?

Also is answer different in C++?

Upvotes: 33

Views: 4721

Answers (3)

2501
2501

Reputation: 25753

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.

Upvotes: 46

gnasher729
gnasher729

Reputation: 52592

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.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234785

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.

Upvotes: 11

Related Questions