how to find the nearest smallest power of 2 to an integer?

Hello all,
I would like to write a code that finds the nearest smallest power of 2 to integers. For instance, if my integer is 6, its smallest nearest power of 2 is 4, while if the integer is 12, the smallest nearest integer is 8. I would appreciate if somebody can help me please. Thanks.

 Accepted Answer

>> N = 6;
>> pow2(floor(log2(N)))
ans =
4
And it is even fully vectorized code, so you can check all of your values at once:
>> pow2(floor(log2([6,12])))
ans =
4 8

3 Comments

Thanks for your answer. Also, I would appreciate if you could tell if I want to have an if else statement in the form of if (N is a power of 2) .... else ... end.
how I can do it?
Option Two (more robust):
[X,~] = log2(N);
if X==0.5
... code
else
... other code
end
Option Two (one line):
if rem(log2(N),1)==0
... code
else
... other code
end

Sign in to comment.

More Answers (0)

Tags

No tags entered yet.

Asked:

Mnr
on 5 May 2015

Commented:

Mnr
on 5 May 2015

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!