Click here to Skip to main content
15,888,113 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Method 1
C++
if ((size & (!(size & (size - 1)))) == size)//if size is exact power of 2
{
    alignedSegmentSize = size;
}
else
{
    while( size != 0)
    {
        size = size << 1;
        alignedSegmentSize = alignedSegmentSize + 1;
    }
    alignedSegmentSize = alignedSegmentSize << 1;
}


Method 2
C++
double alignedSegment = log(static_cast<double>(size))/(log(TWO));
alignedSegment = (ceil((alignedSegment)));
int nextBufferSize = pow(2,alignedSegment);


I wanted to know which method will be more efficient to calculate the nearest power of two for the given value.


Thanks in advance
Posted

1 solution

The one using bitwise operations, of course. Have a look at "Ten Ways to Check if an Integer Is a Power Of Two in C"[^]
 
Share this answer
 
v2
Comments
Member 8576081 30-May-12 6:00am    
Thanx!
Aescleal 30-May-12 8:03am    
5 for the interesting reference - keep me busy for 30 minutes :-)
CPallini 30-May-12 8:12am    
Check out the very book "Hacker's Delight" for more busy time!
:-)
[no name] 30-May-12 22:26pm    
Good answer - now why is also an interesting discussion. This may help:
http://en.wikipedia.org/wiki/Bitwise_operation
CPallini 31-May-12 4:09am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900