regarding MSB, in representing negative decimal to binary equivalent in c++

Viewed 47

I am trying to represent negative Decimal NO. into Binary

and my code working fine

but i have doubt regarding MSB

i know for negative Decimal numbers the MSB is kept 1 in binary form

so what i did for representing 2's complement of a number i kept MSB 0 as currently i am showing 2's complement of positive number

but for representing same 2's complement as binary representation of negative decimal Number

i changed MSB to 1

here's the Output:

binary representation of 8 is 1000
full binary representation of 8 is 00000000000000000000000000001000
1's complement of  8 is 11111111111111111111111111110111
2's complement of  8 is 01111111111111111111111111111000

as negative decimal numbers are basically stored as 2's complement of postive decimal equivalent 
Full  binary representation of -8 is 11111111111111111111111111111000

...Program finished with exit code 0
Press ENTER to exit console.

i wanted to know if printing 2's complement of positive number is equal to binary represention of negative number?? so my approach is right or wrong??? AND here's the code if required

//!!!!this code is not working in my vscode but woeking on online compilers
#include<iostream>
#include<cmath>
using namespace std;

void DeciToBin(int a)
{
    int b=a;
    int sum=0;
    int bit,q=0;

    if(a>0)                                            
    {                                                    
        //binary of 12 is   1100                        
        while(a!=0)
        {
            bit= a&1;

            sum= ( bit * pow(10,q) ) + sum;
            //cout<<pow(10,q)*bit<<endl;
            
        // cout<<sum<<endl;
            a= a >>1;
            //cout<<a<<endl;
            q++;
        }
    }
   
    else
    {
       
       int e=-a;
       int arr[32];  //since integer cant store 32 bit length to representation binary we will operate on array
       int count=0;

       while(e!=0)
        {
            bit= e&1;

            sum= ( bit * pow(10,q) ) + sum;
            //cout<<pow(10,q)*bit<<endl;
            count++;
            e= e >>1;
            q++;
        }
        
       cout<<"binary representation of "<< (-a) <<" is "<<sum<<endl;  
       
       
        int sum2=sum;
        for(int i=0;i<32;i++)
        {
            arr[i]=0;
        }
        
       for (int i = 31; i >=32-count; i--)    //storing everybit in array (normal representation of decimal number in binay)
       {
            arr[i]= sum2%10;
            sum2=sum2/10;
       }
       
       
       cout<<"full binary representation of "<< (-a) <<" is ";  
       for(int i=0;i<32;i++)         //output if decimal number is 6 :  00000000000000000000000000000110 
            cout<<arr[i];
       
       
      //1's complement
      for(int i=0;i<32;i++)
      {
          if(arr[i]==1)
                arr[i]=0;
          else
                arr[i]=1;
      }
      
       cout<<"\n1's complement of  "<< (-a) <<" is ";  
       for(int i=0;i<32;i++)        
            cout<<arr[i];
        
        
        /* convert back to its original binary form, so that we can apply trick to calculate 2's complement
        which works directly on original bibary form of a decimal number */
        for(int i=0;i<32;i++)
        {
          if(arr[i]==1)
                arr[i]=0;
          else
                arr[i]=1;
        }
   
            
        //2's complement by using trick on GFG ** this trick works directly on binary of number not on 1s complement
        for( int i=31 ; i>0 ; i-- )
        {
            if(arr[i]==1)   //check from LSB if the bit is 1 or not , if 1 then turn rest bits in 1(if 0) or in 0(if 1)
            {               // ex  number is 0110100 then it will 1001000 is a 2's complement
            
                for(int j = i-1 ; j>0 ; j--)    // keep j>0 if number is positve and j>=0 if number is negative
                {                                   // as MSB defines if number is negative or +ve ,its for representation only
                    if( arr[j] == 0 )
                        arr[j] = 1;
                }
            break;
            }   
        }
    
        cout<<"\n2's complement of  "<< (-a) <<" is ";  
        for(int i=0 ; i<32 ; i++ )        
            cout<<arr[i];
            
        
        cout<<endl<<endl<<"as negative decimal numbers are basically stored as 2's complement of postive decimal equivalent ";    
        
        arr[0]=1;   //since number is negative i am changing MSB to 1
        cout<<endl<<"Full  binary representation of "<<a<<" is ";
        for(int i=0;i<32;i++)        
            cout<<arr[i];
        
    }   //end of else
    //cout<<"binary Form of "<<b << " is "<<sum<<endl;
}
int main()
{   
    //system("cls");
    int a=-8;
    DeciToBin(a);
    return 0;
}
1 Answers

The output of your program is incorrect even ignoring the fact that the output 2's complement representation is incorrect:

The representation of 8 in 1's or 2's complement matches the original binary. You're attempting to print the negated representations here, i.e. bit sequences representing -8.

Furthermore I don't know where you got that trick of negating a 2's complement number from, but it's either wrong or incorrectly implemented.

Here's an approach I'd consider simpler:

  1. Swap all bits.
  2. Treat the bit sequence as unsigned integer and add 1 taking the resulting value modulo 2^n, i.e. simply drop the carry after you've got the same number of bits the original had.
{
    // Negating a number in 2's complement (which the original value is in) can be done by negating every bit and then
    // adding 1 as if the number was unsigned and ignoring overflow

    int carry = 1; // we're swapping bits and adding 1 at the same time
    for (size_t i = 32; i != 0;)
    {
        --i; // delay the decrement, since the loop variable is unsigned
        auto val = (1 - arr[i]) + carry;
        if (val == 2)
        {
            val = 0;
            carry = 1;
        }
        else
        {
            carry = 0;
        }
        arr[i] = val;
    }
}

Note that there's functionality in the standard library that simplifies this greatly.

#include <bit>
#include <bitset>
#include <cstdint>
#include <iomanip>
#include <iostream>

template<class T>
void PrintBinary(int32_t valueDecimal, T value, char const* representation)
{
    std::cout << std::setw(2) << valueDecimal << " is " << std::bitset<32>(std::bit_cast<uint32_t>(value)) << " in " << representation << '\n';
}

int main()
{
    constexpr uint32_t value = 8;
    constexpr int32_t negatedValue = -value;

    PrintBinary(value, value, "binary");
    PrintBinary(negatedValue, ~value, "1's complement representation");
    PrintBinary(negatedValue, negatedValue, "2's complement representation");
}
Related