Given a binary string, task is to convert this string in to two’s compliment with the help of XOR operator.
Input : 00000101 Output :11111011 Input : 10010 Output : 01110
We have discussed an approach in previous post to find 2’s complement
For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0.
We traverse from the last bot and keep ignoring all 0s until we find a 1. We ignore first 1 also. Then we toggle all bits by doing XOR with 1.
= 0; $i–)
if ($str[$i] == ‘0’ &&
$check_bit == 0)
// xor operator is used
// to flip the
if ($check_bit == 1)
$str[$i] = ($str[$i] – ‘0’) ^ 1 + ‘0’;
// bits after converting in to
// ASCII values
$check_bit = 1;
// if there is no 1 in the string
// so just add 1 in starting of
// string and return
if ($check_bit == 0)
return “1” + $str;
// Driver code
$str = “101”;
// This code is contributed by akt_mit
- 8085 programs to find 2's compliment with carry | Set 2
- Minimum number of given operations required to convert a string to another string
- Python | Check if a given string is binary string or not
- Rearrange given string to maximize the occurrence of string t
- String transformation using XOR and OR
- Check if a string has m consecutive 1's or 0's
- Check if a string follows a^nb^n pattern or not
- Rotations of a Binary String with Odd Value
- Convert String into Binary Sequence
- Find one extra character in a string
- XOR of Prime Frequencies of Characters in a String
- Final string after performing given operations
- Check divisibility of binary string by 2^k
- Construct a binary string following the given constraints
- Check if all the 1's in a binary string are equidistant or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : jit_t