带小数的二进制除法

时间:2016-02-13 13:25:13

标签: binary decimal division

我写了这个小程序,用逗号分隔两个 8位数字和小数( 4位):

void main()
{
    // All numbers are in the format xxxx,xxxx
    unsigned char a = 0b00010000;   // Dividend = 1,0
    unsigned char b = 0b00100000;   // Divisor = 2,0
    unsigned char r = 0;            // Result

    // Align divisor to the left
    while ((b & 0b10000000) == 0)
    {
        b = (b << 1) & 0b11111110;
    }

    // Calculate all 8 bits
    for (unsigned char i = 0; i < 8; ++i)
    {
        if (a < b)
        {
            // Append 0 to the result
            r = (r << 1) & 0b11111110;
        }
        else
        {
            // Append 1 to the result
            r = (r << 1) | 1;

            a = a - b;
        }

        b = b >> 1;
    }

    printBinary(r);
    getchar();
}

但是我的所有结果都是向左移一位数。 所以我的结果比它们应该大2倍。 我是如此倾倒,即使我试图每手计算1/2,我也犯了同样的错误:

0001,0000 / 0010,0000 = 0001,0000

 0001,0000 / 1000,0000
-1000,0000 -> 0
 0001,0000 / 0100,0000
-0100,0000 -> 0
 0001,0000 / 0010,0000
-0010,0000 -> 0
 0001,0000 / 0001,0000
-0001,0000 -> 1
 0000,0000 / 0000,1000
-0000,1000 -> 0
 0000,0000 / 0000,0100
-0000,0100 -> 0
 0000,0000 / 0000,0010
-0000,0010 -> 0
 0000,0000 / 0000,0001
-0000,0001 -> 0

我的错误是什么?

0 个答案:

没有答案