I am trying to see how compiler writes in binary negative numbers, so here is code which should do it
#include <cstdlib>
#include <iostream>
using namespace std;
void complement(int n)
{
int l = n;
int s = 0;
int k = 0;
int m = 0;
while (n != 0)
{
s = n % 2;
n /= 2;
cout << s << " ";
}
cout << endl;
m = ~l + 1;
cout << m << endl;
cout << endl;
while (m != 0)
{
int k = m % 2;
m /= 2;
cout << k << " ";
}
}
int main(int argc, char *argv[])
{
int n;
cin >> n;
cout << endl;
complement(n);
system("PAUSE");
return EXIT_SUCCESS;
}
but strange is that, when I enter 5, for instance, which clearly in binary form is 101 in 3 bit, its complement -5 is represented -10-1? This is what my code's output shows me, but I know that is it not correct, because 2's complement of any number is given by reversing its bits, 0 by 1 and vice-versa, and then +1, in case of 5(101), -5 will be (010+1)=(011). Please help me, how to correct my code so that, it could make complement correctly.
int k = m % 2;definitely reads better thanint k=m%2;.