필터 지우기
필터 지우기

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

조회 수: 46 (최근 30일)
Mnr
Mnr 2015년 5월 5일
댓글: Mnr 2015년 5월 5일
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.

채택된 답변

Stephen23
Stephen23 2015년 5월 5일
편집: Stephen23 2015년 5월 5일
>> 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
Stephen23
Stephen23 2015년 5월 5일
편집: Stephen23 2015년 5월 5일
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
Mnr
Mnr 2015년 5월 5일
Thanks a lot!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

아직 태그를 입력하지 않았습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by