I am having issue with my code giving me the correct output. For example, I am trying to do binary subtraction. The first test case is suppose to test 0x00CD - 0x00AB and the correct output is 0000000000100010 (0x0022). I am getting output of 0000000001100110 (0x0066), which is a few digits off. Can someone help me debug my problem?
#include <stdio.h>
int main(void)
{
int borrow, i, j;
int x[16] = {0}, y[16] = {0}, difference[16] = {0};
int n= 16;
unsigned int hex1, hex2;
scanf("%x %x", &hex1, &hex2);
i = 0;
while (hex1 != 0)
{
x[i] = hex1 % 2;
hex1 = hex1 / 2;
i = i + 1;
}
i = 0;
while (hex2 != 0)
{
y[i] = hex2 % 2;
hex2 = hex2 / 2;
i = i + 1;
}
borrow = 0;
for (i = 15; i >= 0; i--)
{
if(y[i] <= x[i])
{
difference[i] = (x[i] - y[i]);
}
else if (i == n - 1)
{
borrow = 1;
x[i] = x[i] + 2;
difference[i] = (x[i] - y[i]);
}
else
{
j = i + 1;
while (x[j] == 0)
{
j = j + 1;
}
x[j] = x[j] - 1;
j = j - 1;
while (j > i)
{
x[j] = x[j] + 2 - 1;
j = j - 1;
}
difference[i] = (2 + x[i] - y[i]);
}
}
for (i = 15; i >= 0; i--)
printf("%d", difference[i]);
return 0;
}