CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    Question Quickest way to find the most significant bit that is 1...

    Anyone know what the quickest way to find which bit is the most significant bit that is 1?

    For example, say the function I want has the prototype:

    int MsbOn(unsigned long x);

    MsbOn(1) returns 0
    MsbOn(2) returns 1
    MsbOn(3) returns 1
    MsbOn(14) returns 3
    MsbOn(15) returns 3
    MsbOn(16) returns 4
    MsbOn(20000) returns 14

    The only thing I can think of is this:

    #define LN2 (0.69314718055994530941723212145818)

    int MsbOn(unsigned long x)
    {
    return (int)floor(log((double)x)/LN2);
    }

    But this uses floating point math. I'd like to see if there is a quicker, integer way of doing this.

  2. #2
    Join Date
    Sep 2002
    Location
    Singapore
    Posts
    673
    Use bitwise AND operator
    Code:
    if(MyInt & 0x80000000)
    {
    //Do what you want here
    
    
    }
    0x80000000 is 1000 0000 0000 0000 0000 0000 0000 0000 in binary
    Last edited by CBasicNet; November 15th, 2002 at 02:41 PM.

  3. #3
    Join Date
    Sep 2002
    Posts
    1,747

    well...

    You can do as section four of this document suggests. Its a technique I use in certain tight loop calculations....
    */*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/

    "It's hard to believe in something you don't understand." -- the sidhi X-files episode

    galathaea: prankster, fablist, magician, liar

  4. #4
    Join Date
    Sep 2002
    Posts
    1,747

    oh, and...

    If this can be done in x86 assembly, check out the BSR instruction...
    */*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/

    "It's hard to believe in something you don't understand." -- the sidhi X-files episode

    galathaea: prankster, fablist, magician, liar

  5. #5
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245
    Thanks galathaea, that's exactly what I wanted!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured