Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the next Power Of Two of a given number? [duplicate]

Possible Duplicate:
bit twiddling: find next power of two

How to obtain the next Power Of Two of a given number?

For example, i receive the number 138, the next POT number is 256.

i receive the number 112, the next POT is 128.

I need to do an algorithm that calculates that

Thanks

like image 321
NullPointerException Avatar asked Oct 07 '11 10:10

NullPointerException


People also ask

How do you find the power of 2 of a number?

Keep dividing the number by two, i.e, do n = n/2 iteratively until n becomes 1. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.

How do you find previous powers of 2?

The idea is to set all bits on the right-hand side of the most significant set bit to 1 and then drop all but the last set bit from n so that it becomes equal to the previous power of two. For instance, consider number 20. We convert its binary representation 00010100 to 00011111 .

How do you convert a number to the power of 2 in C++?

Powers of 2 to required sum in C++ In this problem, we are given an integer N. Our task is to print the number which when raised to the power of 2 gives the number. To solve this problem, we will divide the number with 2 recursively. By this method, every number can be represented as a power of 2.


1 Answers

A really clever programmer would look at the java.lang.Integer.highestOneBit(int) method, and consider the left-shift operator (<<).

like image 96
Jeff Grigg Avatar answered Oct 11 '22 14:10

Jeff Grigg