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
- String transformation using XOR and OR
- Rotations of a Binary String with Odd Value
- Check if a string follows a^nb^n pattern or not
- Check if a string has m consecutive 1's or 0's
- Check if binary string multiple of 3 using DFA
- XOR of Prime Frequencies of Characters in a String
- Find one extra character in a string
- Convert String into Binary Sequence
- Check divisibility of binary string by 2^k
- Check if a binary string contains consecutive same or not
- Count of occurrences of a "1(0+)1" pattern in a string
- Determine if a string has all Unique Characters
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