#include "stdio.h"
int bdiv( int dividend , int divisor )
{
int remainder = dividend ;
int quotient = 0 ;
int i ;
for( i = 0 ; i < 17 ; i++ )
{
remainder = remainder - divisor ;
if( (remainder & 0x8000) )
{
remainder = remainder + divisor ;
quotient = quotient << 1 ;
}
else
quotient = ( quotient << 1 ) | 0x1 ;
divisor = divisor >> 1 ;
}
return quotient ;
}
int main()
{
int a = 7 ;
int b = 2 ;
printf( "%d\n" , bdiv(a,b) ) ;
}
我试图实现的算法的伪代码:
START
Remainder = Dividend ;
Quotient = 0 ;
1.Subtract Divisor register from remainder and place result in remainder .
2. Test Remainder
2a . If remainder >= 0 shift quotient to right setting rightmost bit to 1
2b. If remainder < 0 , restore the original value of the remainder register . Also shift the quotient register to the left setting the new least significant bit to 0 .
3. Shift the divisor right 1 bit .
4. is it the 33rd repetition ( for 32 bit division ) ? No : GOTO 1
Yes : STOP
我在C中为16位除法编写了这个二进制除法程序,它不能正常工作。谁能告诉我什么不起作用?
输出为131071
,除以7除以2。
答案 0 :(得分:1)
第二个转变需要:
quotient = (( quotient >> 1 ) | 0x1) ;
另外,为什么不:
if (remainder < 0 )
???