How can I multiply and divide using only bit shifting and adding?

后端 未结 14 1633
清歌不尽
清歌不尽 2020-11-22 15:09

How can I multiply and divide using only bit shifting and adding?

14条回答
  •  悲哀的现实
    2020-11-22 15:36

    I translated the Python code to C. The example given had a minor flaw. If the dividend value that took up all the 32 bits, the shift would fail. I just used 64-bit variables internally to work around the problem:

    int No_divide(int nDivisor, int nDividend, int *nRemainder)
    {
        int nQuotient = 0;
        int nPos = -1;
        unsigned long long ullDivisor = nDivisor;
        unsigned long long ullDividend = nDividend;
    
        while (ullDivisor <  ullDividend)
        {
            ullDivisor <<= 1;
            nPos ++;
        }
    
        ullDivisor >>= 1;
    
        while (nPos > -1)
        {
            if (ullDividend >= ullDivisor)
            {
                nQuotient += (1 << nPos);
                ullDividend -= ullDivisor;
            }
    
            ullDivisor >>= 1;
            nPos -= 1;
        }
    
        *nRemainder = (int) ullDividend;
    
        return nQuotient;
    }
    

提交回复
热议问题