The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to 0 and 0 to 1; adding one to the 1s complement of a binary number produces the 2s complement of a binary number.

The binary number in the above figure is equal to 00010100, and its own complement is determined by converting the bit 1 to 0 and 0 to 1 vice versa. Therefore, the alternative to one is 11101011. After calculating one’s add-on, we measure the two’s add-on by adding 1 to one’s add-on, and the result is 11101100.

Let’s create a complement of 2s program.

Analysis of the above program,

First, we input the bits number, and it’s stored in the ‘n’ variable.

We declare character array after entering the number of bits, i.e., char binary [n+1], which holds the binary number. The ‘n’ is the number of bits that we entered in the preceding step; it basically defines the array size.

We declare two more arrays, one complement[n+1] and the other twoscomplement[n+1], respectively. The onescomplement[n+1] array contains those that complement a binary number while the twoscomplement[n+1] array contains a binary number complement to the two.

Initialize the variable carrying, and assign 1 value to the variable.

We input the binary number after declarations.

Now, we actually calculate a binary number’s complement to the one. To do this, for(int i=0;i < n;i++) we construct a loop that iters in the binary array. The condition is checked in for loop, whether the bit is 1 or 0. If the bit is 1 then add addition[i]=0 to supplement another[i]=1. In this way, a binary number complement to one is generated.

We produce the 2s complement of a binary number, after calculating one’s complement. To do this, we build a loop that iters to the starting element from the last element. We have three conditions in the loop:

  • If the add-on bit[i] is 1 and the carry value is 1 then we put 0 in twocomplement[i].
  • If the add-on bit[i] is 0 and the carrying value is 1, then we put 1 in twoscomplement[i] and 0 in carrying.
  • If the above two conditions are wrong, then the addition[i] equals twoscomplement[i].

Pin It on Pinterest

Share This