public static DFix FastDiv(DFix x, DFix y)
{
long xl = x.m_rawValue;
long yl = y.m_rawValue;
long result = 0;
if (yl == 0)
{
throw new DivideByZeroException();
}
bool negative = ((xl >= 0) ^ (yl >= 0)); // 符号位
ulong remainder = (ulong)(xl >= 0 ? xl : -xl); // 余数,被除数
ulong divider = (ulong)(yl >= 0 ? yl : -yl); // 除数
ulong quotient = remainder / divider; // 商数,先求得整数部分
remainder = remainder - quotient * divider;
if(0 == remainder)
{
// 整除了,商数即结果
result = (long)(quotient << FRACTIONAL_PLACES);
}
else
{
// 需要执行小数部分的除法
ulong fraction = 0; // 小数部分
int fractionBits = 0; // 小数点位数,初始为0
while(0 != remainder && fractionBits < FRACTIONAL_PLACES)
{
remainder <<= 1; // 被除数右边补0
fractionBits++; // 小数位数增1
if (remainder >= divider)
{
// 够减,小数部分左移一位并加1,且更新被除数
fraction = (fraction << 1) + 1;
remainder -= divider;
}
else
{
// 不够减,小数部分左移一位并加0
fraction = (fraction << 1) + 0;
}
}
result = (long)((quotient << FRACTIONAL_PLACES) + (fraction & FRACTIONAL_MASK));
}
// 添加符号
result = negative ? -result : result;
return new DFix(result);
}