如何用C编写除法和求模函数

2019-04-13 14:09发布

      一直以来都不明白,如果单片机没有计算模块如何进行求模和除法运算的。于是偶然在调试PIC16F887时发现了以下的2个算法: //== a = b%c =====================================; unsigned char __lbmod(unsigned char dividend, unsigned char divisor) { unsigned char rem; unsigned char counter; counter = 8; rem = 0; do { rem = (rem << 1) | (dividend >> 7); dividend <<= 1; if(divisor <= rem) rem -= divisor; } while(--counter != 0); return rem; } //== a = b/c =====================================; unsigned char __lbdiv(unsigned char dividend, unsigned char divisor) { unsigned char quotient; unsigned char counter; quotient = 0; if(divisor != 0) { counter = 1; while((divisor & 0x80) == 0) { divisor <<= 1; counter++; } do { quotient <<= 1; if(divisor <= dividend) { dividend -= divisor; quotient |= 1; } divisor >>= 1; } while(--counter != 0); } return quotient; }