Results 1 to 3 of 3

Math Help - Calculating the closest number power of 2 to a given number

  1. #1
    Member
    Joined
    Nov 2010
    Posts
    95

    Calculating the closest number power of 2 to a given number

    Hi, i found the following way to do the required job fast, but am unable to understand how it works . Could someone please explain it.

    nearest_pow (uint32_t num)
    {
    uint32_t n = num > 0 ? num - 1 : 0;

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;

    return n;
    }
    Thanks.
    Follow Math Help Forum on Facebook and Google+

  2. #2
    Grand Panjandrum
    Joined
    Nov 2005
    From
    someplace
    Posts
    14,972
    Thanks
    4
    Quote Originally Posted by pranay View Post
    Hi, i found the following way to do the required job fast, but am unable to understand how it works . Could someone please explain it.

    nearest_pow (uint32_t num)
    {
    uint32_t n = num > 0 ? num - 1 : 0;

    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;

    return n;
    }
    Thanks.
    Do you have the pseudo-code?

    Do you know what /= and >> operators do?

    Opps.. It seems you have "|=" (xor) not "/="

    Since this is playing with the bit patterns of the function argument I would suggest that you convert some trial argument to binary and trace this. Also I would be interested in what you think the closest power of 2 means and how that compares with what this code produces.

    CB
    Last edited by CaptainBlack; December 2nd 2010 at 11:45 PM.
    Follow Math Help Forum on Facebook and Google+

  3. #3
    Member
    Joined
    Nov 2010
    Posts
    95
    Thanks, i know about the operators but can't understand their use here to get the result.
    BY nearest power of 2 i mean, suppose i have a number 6 then the next greater number which is closest to it and a power of 2 is 8.
    Follow Math Help Forum on Facebook and Google+

Similar Math Help Forum Discussions

  1. Calculating the number of possible outcomes
    Posted in the Discrete Math Forum
    Replies: 6
    Last Post: October 12th 2010, 10:15 PM
  2. [SOLVED] Calculating number of possible combinations
    Posted in the Statistics Forum
    Replies: 4
    Last Post: October 5th 2010, 04:32 AM
  3. if number closest to zero does sign matter?
    Posted in the Algebra Forum
    Replies: 7
    Last Post: July 28th 2010, 02:05 AM
  4. Matlab Help closest next number
    Posted in the Math Software Forum
    Replies: 3
    Last Post: March 15th 2010, 08:50 PM
  5. Calculating the Number of Combinations?
    Posted in the Statistics Forum
    Replies: 1
    Last Post: March 27th 2006, 03:42 AM

Search Tags


/mathhelpforum @mathhelpforum