开发者

Multiples of powers of two for data alignment

There is a "simple" plain math formula for data alignment contained in the assembly source code of TinyPE, from this address:

http://www.phreedom.org/solar/code/tinype/

This is the formula:

%define round(n, r) (((n+(r-1))/r)*r)

I know that its main intention is to get numbers like n=31 aligned to something like round(n,r)==32 when r=8.

I know that n represents the intended number and r is the rounding "base" multiple. I also know that, given it is simple assembly source code, all operations return integer numbers only, so any decimals are conveniently lost and thus don't cause any calculation "errors".

The question is whether the following explanation is accurate, or if there is a better, more correct one. I don't want to blindly use a snippet I开发者_Python百科 could be misunderstanding somehow.

Also, I would have liked to use number+(round%(number%round)), but it causes division by zero when "number" is an exact multiple of "round".


This formula gets the nearest multiple of a number which is power of two:

In this example our number is 31 and the number we want to have as "base" multiple is 8. It returns 32:

(((31+(8-1))/8)*8)

First we get 8-1, which gives 7. We add it to 31, which gives 38.

Then we divide 38/8, which gives 4.75. From this, the integer value is 4.

This 4 is multiplied by 8, which gives 32.

The logical/mathematical intention of each of these formula parts is as follows:

-- The 8-1 parts makes that an excess be present, whether the original number (in this case 31) is a multiple or not of the base rounding number (in this case 8), and that gives a range that goes through 7 non-multiple numbers and a possible multiple. The -1 causes that we don't get the wrong calculation by going right to the next non-nearest multiple but it just gives an inexact margin to detect the rest of previous "factors".

-- By dividing this exceeded number by the base multiple (8 in this case), in its integer part, we get only the previous factors. The excess that we add to it makes that the number gets aligned to the nearest multiple, if it's within the immediate range without going up to two multiples ahead (hence the -1).

-- By multiplying the purely integer part of this factor (4 in this case) by the base multiple r (8 in this case), we get the exact nearest multiple, without going to the next one. For instance the nearest multiple of 8, starting from 31, is 32, not 40.


I am not quite sure I understand your question, but if you wish to find the power of n closest to a given number x you could try

n^(round(ln(x)/ln(n))

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜