Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to the nearest power of two

Tags:

algorithm

Is there a one line expression (possibly boolean) to get the nearest 2^n number for a given integer?

Example: 5,6,7 must be 8.

like image 934
abbs Avatar asked Dec 09 '10 13:12

abbs


People also ask

What are powers of two?

In mathematics, a power of two is a number of the form 2n where n is an integer, that is, the result of exponentiation with number two as the base and integer n as the exponent.

How do you find the nearest power of 2?

next = pow(2, ceil(log(x)/log(2))); This works by finding the number you'd have raise 2 by to get x (take the log of the number, and divide by the log of the desired base, see wikipedia for more). Then round that up with ceil to get the nearest whole number power. This is a more general purpose (i.e. slower!)

How do you find the largest power of 2 in Python?

def largestPowerOfTwoThatIsAFactorOf(num): factor = 2 while not(num > 0): factor = factor + 1 return factor print(largestPowerOfTwoThatIsAFactorOf(4)) print(largestPowerOfTwoThatIsAFactorOf(15)) print(largestPowerOfTwoThatIsAFactorOf(120)) #For any odd integer, largest power of 2 that's a factor is 1.


1 Answers

Round up to the next higher power of two: see bit-twiddling hacks.

In C:

unsigned int v; // compute the next highest power of 2 of 32-bit v  v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; 
like image 151
Jason S Avatar answered Oct 14 '22 18:10

Jason S