How do I find maximum value of n so that 2^n is less than a value (ex, 500?)

조회 수: 4 (최근 30일)
Ali Hamid
Ali Hamid 2020년 2월 8일
댓글: Walter Roberson 2020년 2월 9일
I am working on making binary code using the power method. So what I am looking to do is make a function where I input a base 10 value and find the binary translation of this value. This will be done by calculating the largest value of 2^n that is smaller than or equall to the input. n will then be the number of rows in the matrix(only for this first instance). From there it will subtract this 2^n value from the input and repeat. The matrix will input going down from the largest n value to fill in the binary code, filling in 1s for when 2 to that n value exists and 0s for when it does not. These are based on calcualtions.
Anyway I am stuck on how to do this for finding max n values that are less than input value, any ideas? From here I feel comfortable creating loops to output binary code.

답변 (1개)

Les Beckham
Les Beckham 2020년 2월 8일
I think you may be looking for log2. Documentation available here: https://www.mathworks.com/help/matlab/ref/log2.html
  댓글 수: 3
Ali Hamid
Ali Hamid 2020년 2월 9일
So after we have the floor(log2(value)), is there a way to output the remainder?
Walter Roberson
Walter Roberson 2020년 2월 9일
closest_power2 = 2.^floor(log2(value));
value = value - closest_power2.

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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by