Inverting a binary number

Hi, I was wondering if anyone could point out to me why this works? I wrote this code, and thought it would just output the number I have put in. However, it outputs the inverse number, which is what I intended for it to do in the first place! The only issue is that if it starts with more than one '1' then it doesn't output on the console, it only shows the 1s (formally zero's).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>

using namespace std;

//Returns the number of digits in X.
int intle(int x)
{
int L=1;
while(x/=10)
L++;
return L;
}


int main()
{
int X;
cout<<"Binary number: ";
cin>>X;
int L=intle(X),array[L];
//Seperates the numbers in X, places them in a new array.
for (int i=0;i<L;i++)
{
    array[i]=X%10;
    X/=10;
}
cout<<"One's compliment: ";
//Outputs the array.
for (int i=0;i<L;i++)
   {
       cout<<array[i];
   }

return 0;
}
If you can explain what this loop is doing, then you'll understand why the array holds the 'reverse' of the int.
1
2
3
4
5
for (int i=0;i<L;i++)
{
    array[i]=X%10;
    X/=10;
}

When you say "modulo" 10, you're grabbing the least significant digit of a base 10 whole number. So if X=154, X%10 = 4. And 4 is what you're putting into array[i].
154 -> a[0] = 4
15  -> a[1] = 5
1   -> a[2] = 1

As far as I can tell, you're not doing what you think you're doing with binary numbers, though. When prompted for a binary number, try typing in 154 and see what happens.
Last edited on
Topic archived. No new replies allowed.