Given 2^n, find n using logarithm

前端 未结 3 2040
醉话见心
醉话见心 2021-01-21 05:53

Given a integer(2^n) which is power of 2, I want to find out n, the index value using logarithm. The formula to find index is : log(number) / log(2). Following is the code snipp

3条回答
  •  逝去的感伤
    2021-01-21 06:14

    When using double math, the log result or quotient may not be exactly the mathematical result but 1 (or 2) next representable double away.

    Calculating log() only returns an exact mathematical result for log(0), all other mathematical results are irrational. All double are rational.

    This may result in an answer like 29.999999..., which saved as an int is 29.

    Recommend using integer math instead


    int mylog2(unsigned long x) {
      int y = 0;
      #if (ULONG_MAX>>16 > 1lu<<16)
        if (x >= 1lu<<32) { x >>= 32; y += 32;
      #endif
      if (x >= 1lu<<16) { x >>= 16; y += 16; }
      if (x >= 1lu<<8) { x >>= 8; y += 8; }
      if (x >= 1lu<<4) { x >>= 4; y += 4; }
      if (x >= 1lu<<2) { x >>= 2; y += 2; }
      if (x >= 1lu<<1) { x >>= 1; y += 1; }
      return y;
    }
    

提交回复
热议问题