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.
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.
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!)
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.
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++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With