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
1's and 2's complement of a Binary Number?
Binary numbers are expressed in base 2, using only the digits '0' and '1'. Each digit in a binary number is called a bit. Understanding 1's and 2's complement is essential for representing signed numbers in computer systems.
1's Complement
One's complement of a binary number is obtained by inverting all bits − changing every '0' to '1' and every '1' to '0'.
Syntax
1's complement = invert all bits Example: 101100 ? 010011
2's Complement
Two's complement of a binary number is obtained by adding 1 to the 1's complement of the binary number.
2's complement = 1's complement + 1 Example: 101100 ? 010011 + 1 = 010100
Example: Finding 1's and 2's Complement
Here's a C program to calculate both complements of a binary number −
#include <stdio.h>
#include <string.h>
int main() {
char binary[10] = "01001011";
char ones_complement[10];
char twos_complement[10];
int length = strlen(binary);
printf("Binary number: %s
", binary);
// Calculate 1's complement
for(int i = 0; i < length; i++) {
if(binary[i] == '0') {
ones_complement[i] = '1';
} else {
ones_complement[i] = '0';
}
}
ones_complement[length] = '\0';
printf("1's complement: %s
", ones_complement);
// Calculate 2's complement (1's complement + 1)
strcpy(twos_complement, ones_complement);
int carry = 1;
for(int i = length - 1; i >= 0 && carry; i--) {
if(twos_complement[i] == '0') {
twos_complement[i] = '1';
carry = 0;
} else {
twos_complement[i] = '0';
}
}
printf("2's complement: %s
", twos_complement);
return 0;
}
Binary number: 01001011 1's complement: 10110100 2's complement: 10110101
Key Points
- 1's complement: Simply flip all bits (0?1, 1?0)
- 2's complement: Add 1 to the 1's complement
- 2's complement is widely used to represent negative numbers in computers
- The range for n-bit 2's complement is -2^(n-1) to 2^(n-1)-1
Conclusion
1's and 2's complement are fundamental concepts in digital systems. While 1's complement inverts all bits, 2's complement adds 1 to the result, making it the standard method for representing signed integers in modern computers.
