707help
707help

Reputation: 11

Why is my binary output different than the expected output?

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;
}

Upvotes: 1

Views: 66

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222477

The logic for your borrow code is broken. When x[i] is greater than y[i] and i is not n-1, you go into this code that looks for a non-zero x[j] to borrow from. But the higher-indexed x[j] were already operated on (because i runs from 15 to 0). You should not be borrowing from them.

Usually subtraction proceeds from the low digits to the high digits (i from 0 to 15). Then, if we need to borrow, we calculate the current digit as if we borrowed, set a counter or flag to remember that we borrowed, and go on to the next digit, incorporating the borrow into the calculations for it.

Alternately, if working from high to low, then, when a borrow is needed, we need to take it from the previously calculated digits (in difference), not from the minuend (x). (And the code for that would have to be alert for running off the high end.)

Upvotes: 1

Related Questions