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
Selected Reading
2's compliment for a given string using XOR ?
In C programming, finding the 2's complement of a binary string can be efficiently done using the XOR operation. The 2's complement is calculated as 1's complement + 1. We use XOR to flip bits and implement a specific algorithm that traverses from the least significant bit (LSB).
Syntax
char* get2sComplement(char* binaryString);
Algorithm
The algorithm works by traversing the binary string from right to left −
- Ignore all trailing zeros until we find the first '1'
- Keep the first '1' unchanged
- Flip all remaining bits using XOR operation
- If no '1' is found, prepend '1' to the string
Example: 2's Complement using XOR
Here's a complete C program that calculates 2's complement using XOR operation −
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* get2sComplement(char* bin) {
int n = strlen(bin);
char* result = (char*)malloc((n + 2) * sizeof(char));
strcpy(result, bin);
int flag = 0; // flag to track if we found the first '1'
// Traverse from right to left (LSB to MSB)
for (int i = n - 1; i >= 0; i--) {
if (result[i] == '0' && !flag) {
continue; // Skip trailing zeros
} else {
if (flag) {
// Flip bit using XOR operation
result[i] = ((result[i] - '0') ^ 1) + '0';
}
flag = 1; // Mark that we found the first '1'
}
}
// If no '1' was found, prepend '1'
if (!flag) {
char* temp = (char*)malloc((n + 2) * sizeof(char));
temp[0] = '1';
strcpy(temp + 1, result);
free(result);
return temp;
}
return result;
}
int main() {
char binary[] = "10110110";
printf("Original binary: %s<br>", binary);
char* complement = get2sComplement(binary);
printf("2's complement: %s<br>", complement);
free(complement);
return 0;
}
Original binary: 10110110 2's complement: 01001010
How It Works
The algorithm follows these steps −
- Find First '1': Traverse from right to left, ignoring all '0's
- Keep First '1': The first '1' encountered remains unchanged
- Flip Remaining Bits: All bits to the left of the first '1' are flipped using XOR with 1
- Handle Edge Case: If the string contains only '0's, prepend '1'
Key Points
- XOR with 1 effectively flips the bit:
0 ^ 1 = 1and1 ^ 1 = 0 - The algorithm has O(n) time complexity where n is the length of binary string
- Memory allocation is used to handle the case where result might be longer than input
- Always free dynamically allocated memory to prevent memory leaks
Conclusion
The XOR-based approach for finding 2's complement is efficient and follows the mathematical definition. It correctly handles all edge cases including strings with trailing zeros and all-zero inputs.
Advertisements
