How do I set a UInt32 to it’s maximum value

1. What is the maximum value for a UInt32?

2. Is there a way I can use the sizeof operator to get the maximum value (as it is unsigned)? So I don’t end up with #defines or magic numbers in my code.

Solution #1:

There’s a macro `UINT32_MAX` defined in `stdint.h` which you can use

``````#include <stdint.h>

uint32_t max = UINT32_MAX;
``````

More about the relevant header `<stdint.h>`:

http://pubs.opengroup.org/onlinepubs/009695299/basedefs/stdint.h.html

Solution #2:

The maximum value for UInt32 is `0xFFFFFFFF` (or 4294967295 in decimal).

`sizeof(UInt32)` would not return the maximum value; it would return 4, the size in bytes of a 32 bit unsigned integer.

Solution #3:

Just set the max using standard hexadecimal notation and then check it against whatever you need. 32-bits is 8 hexadecimals bytes, so it’d be like this:

``````let myMax: UInt32 = 0xFFFFFFFF

if myOtherNumber > myMax {
// resolve problem
}
``````

Solution #4:

The portable way:

``````std::numeric_limits<uint32_t>::max()
``````

Solution #5:

4.294.967.295 is the maximal value or in hexadecimal 0xFFFFFFFF

Solution #6:

An alternative for any unsigned in C or C++ is:

``````anUnsigned = -1;
``````

This is useful since it works for them all, so if you change from `unsigned int` to `unsigned long` you don’t need to go through your code. You will also see this used in a lot of bit fiddling code:

``````anUnsigned |= -(aBoolOrConditionThatWhenTrueCausesAnUnsignedToBeSetToAll1s)
anUnsigned |= -(!aValueThatWhenZeroCausesAnUnsignedToBeSetToAll1s)
anUnsigned |= -(!!aValueThatWhenNonZeroCausesAnUnsignedToBeSetToAll1s)
``````

The downside is that it looks odd, assigning a negative number to an unsigned!

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .