The range of unsigned integers depends on the number of bits used to represent them. A 32-bit unsigned integer, for example, has a range from 0 to 4,294,967,295. Let's break it down.
Unsigned integers are non-negative whole numbers (0 and positive numbers) stored in binary format. Because they are unsigned, all the bits are used to represent the magnitude of the number. This differs from signed integers, where one bit is reserved for the sign (positive or negative).
Here's a table showing the ranges for common unsigned integer sizes:
Size (bits) | Minimum Value | Maximum Value | Formula |
---|---|---|---|
8 | 0 | 255 | 28 - 1 |
16 | 0 | 65,535 | 216 - 1 |
32 | 0 | 4,294,967,295 | 232 - 1 |
64 | 0 | 18,446,744,073,709,551,615 | 264 - 1 |
Explanation:
-
Minimum Value: For any unsigned integer, the minimum value is always 0. This is because there are no bits needed to represent a sign.
-
Maximum Value: The maximum value is calculated as 2n - 1, where 'n' is the number of bits. This is because with 'n' bits, you can represent 2n different values, starting from 0. Therefore, the largest number you can represent is one less than 2n.
Example:
Consider an 8-bit unsigned integer (often called an unsigned char
or uint8_t
). It has 8 bits to represent values.
- The smallest value is when all bits are 0:
00000000
(which is 0 in decimal). - The largest value is when all bits are 1:
11111111
(which is 255 in decimal).
Therefore, the range of an 8-bit unsigned integer is 0 to 255.
The larger the number of bits allocated to an unsigned integer, the larger the range of non-negative values it can represent. This makes unsigned integers useful when you know you will never need to represent negative numbers and need the largest possible positive range.