formula for logarithms to base two of a number

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dynamo
    New Member
    • Apr 2007
    • 51

    formula for logarithms to base two of a number

    Is there a formula for finding logarithms to base two of a number.If so wtat is it.Thanks for any replying.
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    you mean if you don't have a calculator at hand that computes the logarithms?

    there are some series you can use.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      There's a simple integer approximation:

      Code:
      int log2(unsigned int n) {
        int log = 0;
        if (n >= 1<<16) { n >>= 16; log += 16; }
        if (n >= 1<< 8) { n >>=  8; log +=  8; }
        if (n >= 1<< 4) { n >>=  4; log +=  4; }
        if (n >= 1<< 2) { n >>=  2; log +=  2; }
        if (n >= 1<< 1) {           log +=  1; }
        return ((n == 0) ? -1 : log);
      }
      (this assumes C or C++ being used).

      kind regards,

      Jos

      Comment

      • dynamo
        New Member
        • Apr 2007
        • 51

        #4
        thanks for replying.really appreciate it

        Comment

        Working...