I have used the 2's compliment approach to convert a negative number to binary I am getting the answer right
after I converted the number to binary let's say n = -6
- I ignored the negative sign (by making the number positive)
- I took it's 2's compliment
Now if the MSB (Most Significant Bit) is 1 that means the number is negative this ans is stored in newAns
But my doubt is, for me to print the negative binary number since MSB of newAns
was 1
do I have to find 2's compliment of newAns
again or not?
#include<iostream>
#include <math.h>
using namespace std;
int decimalToBinary(int n){
int ans = 0;
int i = 0;
while(n!=0){
int bit = n&1;
ans = (bit * pow(10,i)) + ans;
n = n >> 1;
i++;
}
return ans;
}
int main(){
int n;
cin >> n;
if(n<0){
// if number is negative
n = n*(-1);
int ans = decimalToBinary(n);
// Find 2's compliment of the number
// 1's comp
int newAns = (~ans);
// 2's comp
newAns = newAns+1;
cout << newAns << endl;
} else {
// if number is positive
int ans = decimalToBinary(n);
cout << ans << endl;
}
}