-4

this is part of the code. Here, I want to compare digits by xor. So it suppose to give "0111" but it gives "111" as result. How can I fix it? So it suppose to give "0111" but it gives "111" as result. How can I fix it?

1 and 1 = 0
1 and 0 = 1
0 and 1 = 1
0 and 0 = 0



#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()

{   
    int BinaryRepForDisk1=1101, BinaryRepForDisk2=1010, Disk3=0, xor1, xor2, power=0;

    while(BinaryRepForDisk1!=0)
    {
        xor1=BinaryRepForDisk1%2;
        xor2=BinaryRepForDisk2%2;

        if(xor1==xor2)
        {
            Disk3=Disk3+pow(10,power)*0;
            power++;
        }

        else
        {
            Disk3=Disk3+pow(10,power)*1;
            power++;        
        }   

        BinaryRepForDisk1=BinaryRepForDisk1/10;
        BinaryRepForDisk2=BinaryRepForDisk2/10;
    }   
    printf("%d",Disk3);



    system("pause");
    return 0;
}
user302686
  • 31
  • 6

3 Answers3

0

It is the same number, because you're working with decimals. The only thing is that, if you want the print result to be enforced to be 4 digits and padded with zeroes, use a different print formatter instead:

printf("%04d",Disk3);
sidyll
  • 57,726
  • 14
  • 108
  • 151
  • But I recommend using real binary representations and xor operation, unless you're doing this for some other purpose. – sidyll Mar 23 '16 at 17:44
  • but value of BinaryRepForDisk1 and BinaryRepForDisk2 is changeable. I wrote these values as an example – user302686 Mar 23 '16 at 17:49
0

If you are working with binary numbers, you need to use 0b before the number:

int BinaryDisk1 = 0b1101, BinaryDisk2 = 0b1010;

C also have a xor bit a bit:

int result = BinaryDisk1 ^ BinaryDisk2;

I hope this can help you.

ganchito55
  • 3,559
  • 4
  • 25
  • 46
0

When you use

int BinaryRepForDisk1=1101, BinaryRepForDisk2=1010;

You are initializing BinaryRepForDisk1 to the decimal number 1101, not the binary number 1101. To get the decimal equivalent of the binary 1101, you can use:

int BinaryRepForDisk1= ( (1 << 3) + (1 << 2) + 0 + 1);
// You can use (0 << 1) to keep the familiar structure but its not needed.

If your compiler supports binary literals, you can use:

int BinaryRepForDisk1= 0b1101;

You can make similar adjustments to the value of BinaryRepForDisk2.

R Sahu
  • 204,454
  • 14
  • 159
  • 270