Sub topic 1
Number systems, 2's complement and codes (BCD, Gray)
Prerequisites
This chapter assumes you can read binary and hexadecimal numbers and do elementary algebra. You should also know what AND, OR and NOT mean as logic operations. Nothing else from the tutorial is needed. Later chapters on adders, subtractors and counters rely on the representations covered here.
Positional number systems
A positional number system with base (radix) r writes a number as digits d, where each digit is weighted by a power of r. The value of the digits d(n-1) ... d(1) d(0) . d(-1) d(-2) is the sum of d(i) × r^i. Digits to the right of the radix point have negative exponents.
| System | Base | Digits | Typical use |
|---|---|---|---|
| Binary | 2 | 0, 1 | Hardware |
| Octal | 8 | 0 to 7 | Compact binary (3 bits per digit) |
| Decimal | 10 | 0 to 9 | Humans |
| Hexadecimal | 16 | 0 to 9, A to F | Compact binary (4 bits per digit) |
Converting to decimal
Multiply each digit by its weight and add.
(1101.101) in base 2 = 8 + 4 + 0 + 1 + 0.5 + 0 + 0.125 = 13.625.
Converting from decimal
Handle the integer part and the fraction part separately.
- Integer part: divide repeatedly by the target base. The remainders, read from last to first, are the digits.
- Fraction part: multiply repeatedly by the target base. The integer parts that come out, read in order, are the digits.
Convert 45.375 to binary.
- 45 / 2 gives 22 r1, 11 r0, 5 r1, 2 r1, 1 r0, 0 r1. Reading the remainders upward gives 101101.
- 0.375 × 2 = 0.75 (digit 0), 0.75 × 2 = 1.5 (digit 1), 0.5 × 2 = 1.0 (digit 1). So the fraction is .011.
The result is 101101.011.
A fraction does not always terminate. 0.1 in decimal is a repeating fraction in binary, which is why floating-point hardware cannot store it exactly.
Binary, octal and hexadecimal shortcuts
Group bits in threes (octal) or fours (hex), starting at the radix point and moving outward. Pad with zeros if needed.
def to_base(n: int, base: int) -> str:
digits = "0123456789ABCDEF"
if n == 0:
return "0"
out = []
while n > 0:
n, r = divmod(n, base)
out.append(digits[r])
return "".join(reversed(out))
print(to_base(45, 2)) # 101101
print(to_base(45, 8)) # 55
print(to_base(45, 16)) # 2D
print(int("2D", 16)) # 45The binary 0010 1101 groups as 2 and D in hex, which matches the output above.
Complements and signed numbers
Hardware needs a way to represent negative numbers using only bits. Three schemes appear in GATE questions. Assume n bits in each.
- Sign-magnitude: the top bit is the sign and the other n-1 bits hold the magnitude. It has two zeros (+0 and -0) and needs separate logic for subtraction.
- 1's complement: negate by flipping every bit. It also has two zeros.
- 2's complement: negate by flipping every bit and adding 1. It has one zero, and addition works the same way for signed and unsigned operands.
| Scheme | Range for n bits | Zeros |
|---|---|---|
| Sign-magnitude | -(2^(n-1) - 1) to +(2^(n-1) - 1) | 2 |
| 1's complement | -(2^(n-1) - 1) to +(2^(n-1) - 1) | 2 |
| 2's complement | -2^(n-1) to +(2^(n-1) - 1) | 1 |
How 2's complement works
In an n-bit 2's complement number, the most significant bit has weight -2^(n-1) instead of +2^(n-1). All other bits keep their positive weights.
For 8 bits, 1111 1011 equals -128 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = -5.
The 2's complement of an n-bit number N is 2^n - N. This is why subtraction A - B can be done as A + (2^n - B), and the carry out of the top bit is discarded.
Negation by hand
To find the representation of -6 in 8 bits:
- Write +6: 0000 0110.
- Flip all bits: 1111 1001.
- Add 1: 1111 1010.
A faster method is to copy bits from the right up to and including the first 1, then flip every bit to the left of it.
Sign extension
To widen a 2's complement number, copy the sign bit into the new upper bits. The 4-bit value 1010 (-6) becomes 1111 1010 in 8 bits. Padding with zeros would change the value, so zero extension is only correct for unsigned numbers.
Overflow
Overflow occurs when the true result does not fit in n bits. Adding two numbers of the same sign and getting a result of the opposite sign signals overflow. Adding numbers of opposite signs never overflows.
An equivalent hardware test is that overflow = carry into the sign bit XOR carry out of the sign bit.
Example with 4 bits (range -8 to +7): 0101 (+5) + 0011 (+3) = 1000. The result looks like -8, so overflow happened. The carry into the sign bit is 1 and the carry out is 0, so the XOR is 1.
def add_signed(a: int, b: int, n: int):
mask = (1 << n) - 1
s = (a + b) & mask
# interpret as signed
signed = s - (1 << n) if s >> (n - 1) else s
overflow = not (-(1 << (n - 1)) <= a + b < (1 << (n - 1)))
return format(s, f"0{n}b"), signed, overflow
print(add_signed(5, 3, 4)) # ('1000', -8, True)
print(add_signed(-5, 3, 4)) # ('1110', -2, False)Do not confuse carry with overflow. Carry matters for unsigned arithmetic, and overflow matters for signed arithmetic. The same addition can produce one without the other. For 4 bits, 1111 + 0001 (that is -1 + 1) gives 0000 with a carry out of 1, but no overflow.
Common GATE traps
- The most negative value (-2^(n-1)) has no positive counterpart. Negating 1000 0000 in 8 bits gives 1000 0000 again.
- Comparing 2's complement numbers as if they were unsigned gives wrong answers when signs differ.
- Shifting right: an arithmetic shift copies the sign bit, so it divides by 2 and rounds toward negative infinity. A logical shift fills with 0.
Binary codes
A code assigns a bit pattern to each symbol. Different codes suit different jobs.
BCD (8421)
Binary-coded decimal writes each decimal digit as its own 4-bit binary value. The patterns 1010 to 1111 are invalid.
| Decimal | BCD |
|---|---|
| 0 | 0000 |
| 5 | 0101 |
| 9 | 1001 |
| 25 | 0010 0101 |
| 396 | 0011 1001 0110 |
BCD uses more bits than pure binary for the same range. Two BCD digits take 8 bits and cover 0 to 99, while 8 plain bits cover 0 to 255. Its advantage is easy conversion to and from decimal displays.
BCD addition
Add the two digits in binary. If the 4-bit sum is greater than 9, or if there is a carry out, add 0110 (6) to correct it. The 6 skips the six unused patterns.
Example: 8 + 5.
- 1000 + 0101 = 1101 (13), which is above 9.
- Add 0110: 1101 + 0110 = 1 0011.
- The result is a carry of 1 and a digit of 0011, which reads as 13 in BCD.
def bcd_add_digit(a: int, b: int, cin: int = 0):
s = a + b + cin
if s > 9:
s += 6
return (s >> 4) & 1, s & 0xF # (carry, digit)
print(bcd_add_digit(8, 5)) # (1, 3)
print(bcd_add_digit(4, 3)) # (0, 7)Other weighted and self-complementing codes
Excess-3 is BCD plus 3. Digit 0 is 0011 and digit 9 is 1100. It is self-complementing, which means flipping all four bits gives the code for 9 minus the digit. For example, 2 is 0101 and its flip is 1010, which is the Excess-3 code for 7. The 2421 code has the same property.
Gray code
In a Gray code (reflected binary code), consecutive values differ in exactly one bit. This avoids glitches when a value changes, for example in a rotary encoder, where several bits changing at once could be read as a wrong intermediate value. Gray code also appears in Karnaugh map labels, which you will use later in this tutorial.
The 3-bit sequence is:
| Decimal | Binary | Gray |
|---|---|---|
| 0 | 000 | 000 |
| 1 | 001 | 001 |
| 2 | 010 | 011 |
| 3 | 011 | 010 |
| 4 | 100 | 110 |
| 5 | 101 | 111 |
| 6 | 110 | 101 |
| 7 | 111 | 100 |
Conversion rules:
- Binary to Gray: the MSB is copied, and each other Gray bit is the XOR of the binary bit with the binary bit to its left. In short, g = b XOR (b >> 1).
- Gray to binary: the MSB is copied, and each other binary bit is the XOR of the previous binary bit (already computed) with the current Gray bit.
def bin_to_gray(b: int) -> int:
return b ^ (b >> 1)
def gray_to_bin(g: int) -> int:
b = 0
while g:
b ^= g
g >>= 1
return b
for i in range(8):
print(i, format(bin_to_gray(i), "03b"), gray_to_bin(bin_to_gray(i)))Gray code is cyclic. The last value (100 for 3 bits) differs from the first (000) in one bit.
Parity and other codes
A parity bit is one extra bit chosen so that the total number of 1s is even (even parity) or odd (odd parity). It detects any single-bit error but cannot locate or correct it, and it misses errors that flip two bits. ASCII assigns 7-bit patterns to characters, and a parity bit is sometimes added as the eighth bit.
Choosing a representation
| Need | Good choice | Reason |
|---|---|---|
| Arithmetic on signed integers | 2's complement | One zero, same adder for signed and unsigned |
| Decimal display, exact decimal values | BCD | Digit-by-digit mapping |
| Subtraction using only an adder | 2's complement or Excess-3 | Complement is easy to form |
| Position sensors, counters that must not glitch | Gray | One bit changes per step |
| Error detection | Parity | Cheap, one extra bit |
Worked GATE-style problems
Problem 1. What is the range of a 6-bit 2's complement number?
The range is -2^5 to 2^5 - 1, which is -32 to +31.
Problem 2. Evaluate 0110 1100 - 0011 1010 in 8-bit 2's complement.
- The 2's complement of 0011 1010 is 1100 0110.
- Add: 0110 1100 + 1100 0110 = 1 0011 0010.
- Discard the carry out. The result is 0011 0010, which is 50. Check: 108 - 58 = 50.
Problem 3. How many Gray code patterns of 4 bits differ from 0110 in exactly one bit?
Four. Flipping each of the four bits gives four distinct 4-bit patterns, each at Hamming distance 1.
Exercise
Represent -37 in 8-bit 2's complement, and then give the 8-bit result of adding 100 to it. Does the addition overflow?
Show answer
+37 is 0010 0101. Flip the bits to get 1101 1010 and add 1 to get 1101 1011, so -37 is 1101 1011. Now 100 is 0110 0100. Adding gives 1101 1011 + 0110 0100 = 1 0011 1111. Discarding the carry leaves 0011 1111, which is 63, matching 100 - 37. The operands have opposite signs, so overflow cannot occur.
Exercise
Convert the decimal number 29 to BCD and to 5-bit binary. Then give the Gray code for the 5-bit binary value.
Show answer
BCD is 0010 1001 (digits 2 and 9). Binary is 11101. Gray is the binary value XORed with itself shifted right by one: 11101 XOR 01110 = 10011. So the Gray code is 10011.
Exercise
Add the BCD numbers 0111 0101 (75) and 0010 1000 (28).
Show answer
Add the low digits: 0101 + 1000 = 1101, which is above 9, so add 0110 to get 1 0011. The digit is 0011 with a carry of 1 into the next digit. Add the high digits plus the carry: 0111 + 0010 + 1 = 1010, which is above 9, so add 0110 to get 1 0000. The digit is 0000 with a carry of 1. The result is 0001 0000 0011, which is 103 in BCD.