Bit Hack - Round off to multiple of 8

前端 未结 7 2074
情歌与酒
情歌与酒 2021-01-31 12:42

can anyone please explain how this works (asz + 7) & ~7; It rounds off asz to the next higher multiple of 8.

It is easy to see that ~7 produces 11111000 (8bit repre

7条回答
  •  孤独总比滥情好
    2021-01-31 13:03

    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);
    }
    

提交回复
热议问题