Advertisement

Wednesday, 12 September 2018

Two’s Complement of a Binary Number in C++ [Short Method]




The negative of a binary number represented by its two’s complement.


In general (long method) we switch all ones to zeros and all zeros to ones and then adding one to the result to attain the two’s complement of a number.

We can also get the two’s complement in an efficient manner (short method) described below. 

Input:  num = "1000100"
Output:        0111100
Description: Start traversing the string (num) from end, we got first '1' at index 4 then just flip the remaining bits from 0 to 3 indexes to make the 2's complement.

Input:  num = "0000"
Output:       10000
Description: As there is no 1 in the string so just
Append '1' in the starting.



#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
     char num[7];   
     int j;
     cout<<"Enter the number\n";
     gets(num);
     for(int i=sizeof(num)-1;i>=0;i--)
     {
          if(num[i]=='0')
          {
              num[i]='0';
          }
          else
          {
              num[i]='1';
              j=i;
              break;
          }
     }
     for(j=j-1;j>=0;j--)
     {
          if(num[j]=='1')
          {
              num[j]='0';
          }
          else
          {
              num[j]='1';
          }
     }
     cout<<"\n Conversion is \n";
     puts(num);
     return 0;
}








Related Articles

No comments:

Post a Comment