Bit Hack - Round off to multiple of 8

穿精又带淫゛_ 提交于 2019-12-02 18:53:34

Well, if you were trying to round down, you wouldn't need the addition. Just doing the masking step would clear out the bottom bits and you'd get rounded to the next lower multiple.

If you want to round up, first you have to add enough to "get past" the next multiple of 8. Then the same masking step takes you back down to the multiple of 8. The reason you choose 7 is that it's the only number guaranteed to be "big enough" to get you from any number up past the next multiple of 8 without going up an extra multiple if your original number were already a multiple of 8.

In general, to round up to a power of two:

unsigned int roundTo(unsigned int value, unsigned int roundTo)
{
    return (value + (roundTo - 1)) & ~(roundTo - 1);
}

It's actually adding 7 to the number and rounding down.

This has the desired effect of rounding up to the next multiple of 8. (Adding +8 instead of +7 would bump a value of 8 to 16.)

The +7 isn't to produce an exact multiple of 8, it's to make sure you get the next highest multiple of eight.

edit: Beaten by 16 seconds and several orders of quality. Oh well, back to lurking.

Well, the mask would produce an exact multiple of 8 by itself. Adding 7 to asz ensures that you get the next higher multiple.

Without the +7 it will be the biggest multiple of 8 less or equal to your orig number

Adding 7 does not produce a multiple of 8. The multiple of 8 is produced by anding with ~7. ~7 is the complement of 7, which is 0xffff fff8 (except using however many bits are in an int). This truncates, or rounds down.

Adding 7 before doing that insures that no value lower than asz is returned. You've already worked out how that works.

Uhh, you just answered your own question??? by adding 7, you are guaranteeing the result will be at or above the next multiple of 8. truncating then gives you that multiple.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!