Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Binary Number System - Overflow in Arithmetic Addition in C/C++?
The 2's complement number system is widely implemented in computer architecture for representing signed integers. In an N-bit 2's complement system, numbers can be represented from -2n-1 to 2n-1 - 1.
For example −
- 4-bit system represents numbers from -8 to 7
- 5-bit system represents numbers from -16 to 15
Overflow occurs when adding two N-bit 2's complement numbers and the result is too large to fit into the N-bit representation.
Syntax
// Overflow detection formula overflow = carry_in_msb ^ carry_out_msb
Understanding Overflow
A computer uses N-bit fixed registers. When adding two N-bit numbers, the result may require N+1 bits. The extra bit is stored in a carry flag, but carry doesn't always indicate overflow.
Overflow Detection Rules
Overflow occurs when −
- Addition of two positive numbers yields a negative result
- Addition of two negative numbers yields a positive result
Instead of checking all three MSBs (operands and result), overflow can be detected by comparing carry-in and carry-out of the MSB position −
Example: Detecting Overflow in C
Here's a practical implementation to detect overflow in 4-bit addition −
#include <stdio.h>
int detectOverflow(int a, int b, int sum, int bits) {
int max_pos = (1 << (bits - 1)) - 1;
int min_neg = -(1 << (bits - 1));
// Check if result is outside valid range
if (sum > max_pos || sum < min_neg) {
return 1; // Overflow detected
}
return 0; // No overflow
}
int main() {
int bits = 4; // 4-bit system
int max_pos = (1 << (bits - 1)) - 1; // 7
int min_neg = -(1 << (bits - 1)); // -8
printf("4-bit range: %d to %d\n", min_neg, max_pos);
// Test cases
int test_cases[][2] = {{7, 1}, {-8, -1}, {3, 4}, {-5, -2}};
int num_tests = 4;
for (int i = 0; i < num_tests; i++) {
int a = test_cases[i][0];
int b = test_cases[i][1];
int sum = a + b;
printf("\nTest: %d + %d = %d\n", a, b, sum);
if (detectOverflow(a, b, sum, bits)) {
printf("OVERFLOW detected!\n");
} else {
printf("No overflow\n");
}
}
return 0;
}
4-bit range: -8 to 7 Test: 7 + 1 = 8 OVERFLOW detected! Test: -8 + -1 = -9 OVERFLOW detected! Test: 3 + 4 = 7 No overflow Test: -5 + -2 = -7 No overflow
Key Points
- Overflow occurs when the result exceeds the representable range of N-bit 2's complement system
- Carry flag alone doesn't indicate overflow ? it's the XOR of carry-in and carry-out from MSB
- Overflow detection:
overflow = carry_in_msb ^ carry_out_msb - Hardware implements this using a simple XOR gate
Conclusion
Overflow in 2's complement addition can be efficiently detected by comparing carry-in and carry-out of the MSB position. This method requires only a simple XOR operation, making it ideal for hardware implementation.
