Sub topic 2
Unsigned Integers and Their Range
This chapter assumes that you know decimal and binary place values, powers of two, and basic binary addition. An unsigned integer stores only non-negative whole numbers. Every bit contributes a non-negative place value.
Positional value of an unsigned binary number
For an \(n\)-bit binary number, the rightmost bit has weight \(2^0\). Each position to its left has twice the previous weight.
For example:
\[ 101101_2 = 1(2^5)+0(2^4)+1(2^3)+1(2^2)+0(2^1)+1(2^0) \]
\[ =32+8+4+1=45_{10} \]
The same value can be grouped into four-bit sections and written in hexadecimal:
\[ 1011012 = 0010\ 11012 = 2D_{16} \]
Leading zeroes do not change a value, but they show the storage width. Thus, 00101101 is an 8-bit representation of 45.
Range of an n-bit unsigned integer
An \(n\)-bit unsigned number has \(2^n\) possible bit patterns. The smallest pattern is all zeroes, and the largest is all ones.
| Bit pattern | Value | Meaning |
|---|---|---|
| `00000000` for 8 bits | 0 | Minimum |
| `11111111` for 8 bits | \(2^8-1=255\) | Maximum |
| `10000000` for 8 bits | 128 | A middle value |
Therefore, the range is:
\[ 0 \leq x \leq 2^n-1 \]
The maximum value is obtained by summing every place value:
\[ 2^{n-1}+2^{n-2}+\cdots+2^1+2^0=2^n-1 \]
A useful shortcut is:
- \(n=8\): 0 to 255
- \(n=16\): 0 to 65,535
- \(n=32\): 0 to \(4,294,967,295\)
The number of bits needed for a positive integer \(x\) is:
\[ \lfloor \log_2 x \rfloor+1 \]
For \(x=45\), \(\lfloor\log_2 45\rfloor+1=5+1=6\), so six bits are sufficient.
def unsigned_range(bits):
if bits < 1:
raise ValueError("bits must be positive")
return 0, (1 << bits) - 1
for bits in (8, 16, 32):
print(bits, unsigned_range(bits))Overflow and wraparound
If a calculation produces a value larger than \(2^n-1\), it cannot fit in \(n\) unsigned bits. In hardware that keeps only the low \(n\) bits, the result wraps modulo \(2^n\).
For 8 bits:
\[ 255+1=256 \]
The binary result is 1 00000000. Keeping only eight bits gives 00000000, so the stored result is zero and a carry-out is produced.
GATE-style shortcut
When a question asks for the smallest number of unsigned bits needed to represent values from 0 through \(M\), choose the smallest \(n\) satisfying:
\[ 2^n-1 \geq M \]
For example, \(M=1000\). Since \(2^9-1=511\) and \(2^{10}-1=1023\), the answer is 10 bits.
Exercise
What is the range of a 12-bit unsigned integer, and what 12-bit value represents decimal 3000?
Show answer
The range is 0 through 2^12 - 1 = 4095. Since 3000 = 2048 + on 952? Correctly, 3000 = 2048 + 952 = 2048 + 512 + 256 + 128 + 32 + 16 + 8, its binary representation is 101110111000.